我想在我的绘图上画圆。为此,我决定使用 matplotlib 中的 patch.Circle 类。 Cirlce 对象使用 radius 参数来设置圆的半径,但如果轴比不是 1(参见我的图),如何以正确的比例绘制圆? 我画圆的代码是:
rect = patches.Circle(xy=(9, yaxes),radius= 2, linewidth=3, edgecolor='r', facecolor='red',alpha=0.5)
ax.add_patch(rect)
最佳答案
您可以使用ax.transData
变换 1,1
与 0,0
并获得 x 与 y 方向的变形。该比率可用于了解圆的水平与垂直尺寸。
如果您只需要使用相对于轴的坐标来放置圆,则可以使用 plt.scatter
和 transform=ax.transAxes
。请注意,尺寸是基于“点”的“面积”度量(“点”是 1/72 英寸)。
以下示例代码使用数据坐标来定位“圆”(使用椭圆),并使用 x 坐标作为半径。使用轴坐标放置红色圆圈。
from matplotlib import pyplot as plt
from matplotlib.patches import Ellipse
import pandas as pd
import numpy as np
# plot some random data
np.random.seed(2021)
df = pd.DataFrame({'y': np.random.normal(10, 100, 50).cumsum() + 2000},
index=np.arange(101, 151))
ax = df.plot(figsize=(12, 5))
# find an "interesting" point
max_ind = df['y'].argmax()
max_x = df.index[max_ind]
max_y = df.iloc[max_ind]['y']
# calculate the aspect ratio
xscale, yscale = ax.transData.transform([1, 1]) - ax.transData.transform([0, 0])
# draw the ellipse to be displayed as circle
radius_x = 4
radius_y = radius_x * xscale / yscale
ax.add_patch(Ellipse((max_x, max_y), radius_x, radius_y, color='purple', alpha=0.4))
# use ax.scatter to draw a red dot at the top left
ax.scatter(0.05, 0.9, marker='o', s=2000, color='red', transform=ax.transAxes)
plt.show()
关于绘制椭圆的一些说明:
- 这仅适用于线性坐标,不适用于例如对于对数刻度或极坐标
- 代码假设轴限制和轴位置之后都不会改变,因为它们会扭曲纵横比
关于python - 无法绘制正确比例的圆 Matplotlib Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70056112/