python - 无法绘制正确比例的圆 Matplotlib Python

标签 python pandas matplotlib

我想在我的绘图上画圆。为此,我决定使用 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)

在此示例中,yaxes 等于 206(因为我想将其绘制为左上角)。 这是我使用此代码得到的图片: enter image description here

但我想要这样的东西: enter image description here

最佳答案

您可以使用ax.transData变换 1,10,0 并获得 x 与 y 方向的变形。该比率可用于了解圆的水平与垂直尺寸。

如果您只需要使用相对于轴的坐标来放置圆,则可以使用 plt.scattertransform=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()

drawing a circle with radius in x coordinates

关于绘制椭圆的一些说明:

  • 这仅适用于线性坐标,不适用于例如对于对数刻度或极坐标
  • 代码假设轴限制和轴位置之后都不会改变,因为它们会扭曲纵横比

关于python - 无法绘制正确比例的圆 Matplotlib Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70056112/

相关文章:

python - pyplot 在图例中组合多个线标签

python - 我正在创建一个 tkinter gui,我需要将其设为一个线程。但线程不起作用

python - 机器学习: How to regularize output and force them to be away from 0?

Python 对字符串值进行 Groupby

python - csv - 如何使用 python 和 pandas 获取某一行中的行值?

python - 是否可以使用 matplotlib 绘制时间线?

Python 3 : Programmatically converting list of hex numbers to binary

python - 函数中的列积分

python-3.x - 在groupby聚合函数中传递参数

python - 如何将图形图例重新定位到子图形中