python - Matplotlib 极坐标绘图 : displaying polar tickmarks in degrees, 十进制格式

标签 python matplotlib plot axis-labels polar-coordinates

我正在尝试按照指定格式(即带两位小数的 float )以度数标记 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))

最佳答案

极坐标图的内部单位是弧度。因此,刻度的位置以弧度表示,这些是您需要格式化的数字。您可以使用 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

关于python - Matplotlib 极坐标绘图 : displaying polar tickmarks in degrees, 十进制格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54681008/

相关文章:

python - python 中带有 slider 的散点图

matplotlib - 描述 Julia 中二维空间中数据点密度的图

python - ConfigParser - 如果文件不存在则创建文件

python - 转换以前缀表示法给出的表达式,识别公共(public)子表达式和依赖项

python - 值错误 : Supply a 'c' kwarg or a 'color' kwarg but not both; they differ but their functionalities overlap

python - Cartopy 和 matplotlib TypeError : unhashable type: 'MultiLineString'

r - 在 ggplot boxplot 中的填充组内显示单独的均值

python - 为什么表格在 Python-markdown 中不起作用?

python - 如何 !rm python_var (在 Jupyter 笔记本中)

python - matplotlib的 "barh"中height变量的单位是什么?