Matplotlib极坐标图:以十进制格式显示度数的极坐标刻度

时间:2019-02-13 23:26:49

标签: python matplotlib plot axis-labels polar-coordinates

我试图按照指定格式(即,带有两个小数位的浮点数),以的方式在Matplotlib中的极区图上标记刻度线,但是这样做这两个都没有明确支持。

我可以将刻度标记标记为度数,并带有指定的小数位,但不能同时使用这两者。请注意,Matplotlib默认以度为单位的刻度线:

但是在我使用ax.xaxis.set_major_formatter()对刻度线应用格式之后,将显示弧度:enter image description here

如何在指定小数格式的同时强制执行度数格式?

注意:将刻度标记转换为度数(例如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))

2 个答案:

答案 0 :(得分:3)

极坐标图的内部单位是辐射。因此,刻度线的位置以辐射度给出,这些是您需要格式化的数字。您可以使用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()

enter image description here

答案 1 :(得分:1)

或者,您可以使用PercentFormatterxmax是对应于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)) # <---

enter image description here