matplotlib 极坐标子图出现错误“AxesSubplot”中没有属性“极坐标”“

wgmfuz8q  于 2023-03-03  发布在  其他
关注(0)|答案(1)|浏览(224)

同样的问题已经在这个链接中报告。然而,在我的情况下,我只需要在整个2*2图中的一个极子图。
我的python在3.9.13
使用subplot_kw=dict(polar=True)将整个图转换为极坐标图,这不是我的本意。
“这是我的代码:“

import matplotlib.pyplot as plt
import numpy as np

# random data
data_hist = np.random.randn(1000)

data_line = np.random.randn(50).cumsum()

data_scatter_x = np.random.randn(50)
data_scatter_y = np.random.randn(50)

data_radar = np.random.rand(3) * 2 * np.pi

# 2*2 figure
fig, axs = plt.subplots(2, 2)
axs = axs.flatten()

axs[0].hist(data_hist, bins=50, color='steelblue', edgecolor='black')
axs[0].set_title('Histogram')

axs[1].plot(data_line, color='r', marker='o')
axs[1].set_title('Line plot')

axs[2].scatter(data_scatter_x, data_scatter_y, color='g')
axs[2].set_title('Scatter plot')

axs[3].polar(data_radar, data_radar, marker='o')
axs[3].set_title('Radar plot')

plt.tight_layout()
plt.show()
5lhxktic

5lhxktic1#

plt.subplots的默认投影为rectilinear,请检入Doc matplotlib.pyplot.subplot,如果要更改子图中的投影,则需要删除ax[3]并重新定义它。

import matplotlib.pyplot as plt
import numpy as np

# random data
data_hist = np.random.randn(1000)

data_line = np.random.randn(50).cumsum()

data_scatter_x = np.random.randn(50)
data_scatter_y = np.random.randn(50)

r = np.arange(0, 2, 0.1)
theta = 2 * np.pi * r

# 2*2 figure
fig, axs = plt.subplots(2, 2)
axs = axs.flatten()

axs[0].hist(data_hist, bins=50, color='steelblue', edgecolor='black')
axs[0].set_title('Histogram')

axs[1].plot(data_line, color='r', marker='o')
axs[1].set_title('Line plot')

axs[2].scatter(data_scatter_x, data_scatter_y, color='g')
axs[2].set_title('Scatter plot')

axs[3].remove()
axs[3] = plt.subplot(224, projection='polar')
axs[3].plot(theta, r, marker='o')
axs[3].set_title('Radar plot')

plt.tight_layout()
plt.show()

下图:

相关问题