我试图在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()
或者,您可以使用PercentFormatter
。这里xmax
是对应于100%的值。根据您转换为百分比,100%将对应于np.pi*100/180
的弧度值。
我正在通过评论#
突出显示增加的三行代码
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import PercentFormatter # <---
minTheta = 0.42; maxTheta = 0.55
fig = plt.figure()
ax = fig.add_subplot(111, projection='polar')
ticks = np.linspace(minTheta, maxTheta, 4)
ax.set_xticks(ticks)
ax.set_thetamin(np.rad2deg(minTheta))
ax.set_thetamax(np.rad2deg(maxTheta))
xmax = np.pi*100/180 # <---
ax.xaxis.set_major_formatter(PercentFormatter(xmax, decimals=2)) # <---