为什么matplotlib将我的圆圈绘制为椭圆形?

use*_*756 22 python matplotlib

有没有办法让matplotlib绘制一个完美的圆圈?它们看起来更像椭圆形.

Yan*_*ann 36

只是为了扩展DSM的正确答案.默认情况下,绘图沿一个轴在另一个轴上具有更多像素.添加圆圈时,传统上会添加数据单元.如果您的轴具有对称范围,则意味着沿x轴的一步将包含与沿y轴一步不同的像素数.因此,数据单元中的对称圆在您的像素单位中是不对称的(您实际看到的内容).

正如DSM正确指出的那样,您可以强制x和y轴每个数据单元具有相同数量的像素.这是使用plt.axis("equal")ax.axis("equal")方法完成的(其中ax是一个实例Axes).

您还可以绘制一个Ellipse适当缩放的图形,使其在图表上看起来像一个圆圈.以下是此类案例的示例:

import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse, Circle


fig = plt.figure()
ax1 = fig.add_subplot(211)
# calculate asymmetry of x and y axes:
x0, y0 = ax1.transAxes.transform((0, 0)) # lower left in pixels
x1, y1 = ax1.transAxes.transform((1, 1)) # upper right in pixes
dx = x1 - x0
dy = y1 - y0
maxd = max(dx, dy)
width = .15 * maxd / dx
height = .15 * maxd / dy

# a circle you expect to be a circle, but it is not
ax1.add_artist(Circle((.5, .5), .15))
# an ellipse you expect to be an ellipse, but it's a circle
ax1.add_artist(Ellipse((.75, .75), width, height))
ax2 = fig.add_subplot(212)

ax2.axis('equal')
# a circle you expect to be a circle, and it is
ax2.add_artist(Circle((.5, .5), .15))
# an ellipse you expect to be an ellipse, and it is
ax2.add_artist(Ellipse((.75, .75), width, height))

fig.savefig('perfectCircle1.png')
Run Code Online (Sandbox Code Playgroud)

导致这个数字:

在此输入图像描述

或者,您可以调整您的数字,使其Axes为正方形:

# calculate dimensions of axes 1 in figure units
x0, y0, dx, dy = ax1.get_position().bounds
maxd = max(dx, dy)
width = 6 * maxd / dx
height = 6 * maxd / dy

fig.set_size_inches((width, height))

fig.savefig('perfectCircle2.png')
Run Code Online (Sandbox Code Playgroud)

导致:

在此输入图像描述

请注意具有该axis("equal")选项的第二个轴现在具有相同的x和y轴范围.该图已经缩放,以便每个的日期单位由相同数量的像素表示.

您也可以将轴调整为方形,即使数字不是.或者您可以将圆的默认变换更改为None,这意味着使用的单位是像素.我现在很难成功地做到这一点(圆圈是一个圆圈,但不是我想要它的地方).


Apo*_*los 8

我相信更简单的事情是添加以下内容:

ax.set_aspect('equal')
Run Code Online (Sandbox Code Playgroud)