我正在尝试按照指定格式(即带两位小数的 float )以度数标记 Matplotlib 中极扇区图上的刻度线,但是这样做这两者都没有得到明确的支持。
我可以将刻度线标记为具有指定小数位的度数或,但不能同时标记这两者。请注意,Matplotlib 默认为以度为单位的刻度线:
但在我使用 ax.xaxis.set_major_formatter()
将格式应用于刻度线后,显示的是弧度:
如何在指定小数格式的同时强制使用度数格式?
注意:将刻度线转换为度数(例如,numpy.rad2deg
)不起作用,因为 ax.set_xticks()
仅将参数解释为弧度(但, Matplotlib 默认将它们显示为度数...)
示例代码:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import FormatStrFormatter
minTheta = 0.42; maxTheta = 0.55
fig = plt.figure()
ax = fig.add_subplot(111, projection='polar')
#create four tick labels (in radians) dynamically based on the theta range
ticks = np.linspace(minTheta, maxTheta, 4)
ax.set_xticks(ticks)
#disable or enable the following line to change the tick display format*************
ax.xaxis.set_major_formatter(FormatStrFormatter('%.2f'))
#Adjust the sector window: you must call these AFTER setting the ticks, since setting the ticks
#actually adjusts the theta range window. This must be in degrees.
ax.set_thetamin(np.rad2deg(minTheta))
ax.set_thetamax(np.rad2deg(maxTheta))
最佳答案
极坐标图的内部单位是弧度。因此,刻度的位置以弧度表示,这些是您需要格式化的数字。您可以使用 FuncFormatter
来做到这一点。
rad2fmt = lambda x,pos : f"{np.rad2deg(x):.2f}°"
ax.xaxis.set_major_formatter(FuncFormatter(rad2fmt))
完整的例子如下:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter
minTheta = 0.42; maxTheta = 0.55
fig = plt.figure()
ax = fig.add_subplot(111, projection='polar')
#create four tick labels (in radians) dynamically based on the theta range
ticks = np.linspace(minTheta, maxTheta, 4)
ax.set_xticks(ticks)
#disable or enable the following line to change the tick display format*
rad2fmt = lambda x,pos : f"{np.rad2deg(x):.2f}°"
ax.xaxis.set_major_formatter(FuncFormatter(rad2fmt))
#Adjust the sector window: you must call these AFTER setting the ticks, since setting the ticks
#actually adjusts the theta range window. And it must be in degrees.
ax.set_thetamin(np.rad2deg(minTheta))
ax.set_thetamax(np.rad2deg(maxTheta))
plt.show()
关于python - Matplotlib 极坐标绘图 : displaying polar tickmarks in degrees, 十进制格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54681008/