如何在matplotlib中格式化极坐标图

2024-09-28 22:29:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些制作极坐标图的示例代码:

import numpy as np
import matplotlib.pyplot as plt

azimuths = np.radians(np.linspace(0, 180, 90))
zeniths = np.arange(50, 5050, 50)

r, theta = np.meshgrid(zeniths, azimuths)
values = 90.0+5.0*np.random.random((len(azimuths), len(zeniths)))

fig, ax = plt.subplots(subplot_kw=dict(projection='polar'))
ax.set_theta_zero_location("W")
pp = plt.contourf(theta, r, values, label='tmp')
cbar = plt.colorbar(pp, orientation='vertical')
cbar.ax.set_ylabel('scale label')
plt.show()

给我的感觉是:

enter image description here

……但我更喜欢这样:

enter image description here

…中间有空间,只显示0到180度。有人知道有什么方便的方法吗?在


Tags: importlenasnppltrandomaxlabel
1条回答
网友
1楼 · 发布于 2024-09-28 22:29:31

我不确定这有多方便,但这里有一个可破解的解决方案(取自here):

import numpy as np

import mpl_toolkits.axisartist.floating_axes as floating_axes
from matplotlib.projections import PolarAxes
from mpl_toolkits.axisartist.grid_finder import FixedLocator, MaxNLocator, \
             DictFormatter
import matplotlib.pyplot as plt

tr = PolarAxes.PolarTransform()

degree_ticks = lambda d: (d*np.pi/180, "%d$^\\circ$"%(360-d))
angle_ticks = map(degree_ticks, np.linspace(180, 360, 5))
grid_locator1 = FixedLocator([v for v, s in angle_ticks])
tick_formatter1 = DictFormatter(dict(angle_ticks))
tick_formatter2 = DictFormatter(dict(zip(np.linspace(1000, 6000, 6),
                                         map(str, np.linspace(0, 5000, 6)))))

grid_locator2 = MaxNLocator(5)

gh = floating_axes.GridHelperCurveLinear(tr,
                                         extremes=(2*np.pi, np.pi, 1000, 6000),
                                         grid_locator1=grid_locator1,
                                         grid_locator2=grid_locator2,
                                         tick_formatter1=tick_formatter1,
                                         tick_formatter2=tick_formatter2)

fig = plt.figure()
ax = floating_axes.FloatingSubplot(fig, 111, grid_helper=gh)
fig.add_subplot(ax)

azimuths = np.radians(np.linspace(180, 360, 90)) # added 180 degrees
zeniths = np.arange(1050, 6050, 50) # added 1000

r, theta = np.meshgrid(zeniths, azimuths)
values = 90.0+5.0*np.random.random((len(azimuths), len(zeniths)))

aux_ax = ax.get_aux_axes(tr)
aux_ax.patch = ax.patch
ax.patch.zorder = 0.9

aux_ax.contourf(theta, r, values) # use aux_ax instead of ax

plt.show()

请注意(为了获得原点附近的空间),您需要将所有数据点沿半径方向移动1000,并在θ方向移动pi(以获得下半球)。 这就产生了:

enter image description here

相关问题 更多 >