如何使用 matplotlib 在极坐标图上放置文本?

How to put text on polar chart using matplotlib?

这是matplotlib文档中的demo Scatter plot on polar axis

import numpy as np
import matplotlib.pyplot as plt


# Fixing random state for reproducibility
np.random.seed(19680801)

# Compute areas and colors
N = 150
r = 2 * np.random.rand(N)
theta = 2 * np.pi * np.random.rand(N)
area = 200 * r**2
colors = theta

fig = plt.figure()
ax = fig.add_subplot(projection='polar')
c = ax.scatter(theta, r, c=colors, s=area, cmap='hsv', alpha=0.75)

现在我想用一些文字替换这些点,比如

我应该对这些代码做哪些修改?

另外,我也想用图片代替文字,可以吗?

谢谢!!!

您删除了 ax.scatter 部分,而是使用 ax.text。但请注意,您还需要以极坐标传递文本的坐标。例如。: ax.text(np.pi / 2, 60, 'people', fontsize=20, color='red').

给你:

import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(projection='polar')

for text,xytext, color in zip(*[['cat', 'car', 'people'],[(0.5, 0.3),(0.5, 0.7),(0.1, 0.5)],['b', 'g','r']]):
    ax.annotate(text,
                xy=(0,0),  # theta, radius
                xytext=xytext,    # fraction, fraction
                textcoords='figure fraction',
                horizontalalignment='left',
                verticalalignment='bottom',
                color=color,
                size=20
                )

plt.show()

对于插入图像,有以下 demo

这是原代码:

import numpy as np
import matplotlib.pyplot as plt


# Fixing random state for reproducibility
np.random.seed(19680801)

# Compute areas and colors
N = 150
r = 2 * np.random.rand(N)
theta = 2 * np.pi * np.random.rand(N)
area = 200 * r**2
colors = theta

fig = plt.figure()
ax = fig.add_subplot(projection='polar')
c = ax.scatter(theta, r, c=colors, s=area, cmap='hsv', alpha=0.75)

如果添加这两行:

plt.text(0.67, 0.9, 'I am cartesian coordinate', transform=plt.gcf().transFigure)
plt.text(np.pi, r[len(r)-1], 'I am polar coordinate')

你会得到

如果您添加此代码:

im = Image.open('smurf.png')
newax = fig.add_axes([0.5, 0.5, 0.2, 0.2], zorder=1)
newax.imshow(im)
newax.axis('off')
newax = fig.add_axes([0.3, 0.3, 0.2, 0.2], zorder=1)
newax.imshow(im)
newax.axis('off')

你会得到

但需要换算计算才能得到极坐标