Matplotlib 极坐标绘图:以度数显示极坐标刻度线,采用十进制格式

Matplotlib polar plotting: displaying polar tickmarks in degrees, with decimal format

我试图在 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)) # <---