我正试着画一个被对角线截断的圆.以下是我的不起作用的代码:

import matplotlib.pyplot as plt

# Create the circle with radius 6
circle = plt.Circle((0, 0), 6, color='r', fill=False)

# Set up the plot (reuse the previous grid settings)
plt.figure(figsize=(8, 8))
plt.xlim(0, 10)
plt.ylim(0, 10)
plt.grid()

# Add the circle to the plot
ax = plt.gca()
ax.add_patch(circle)

# Draw a diagonal line
plt.plot([0, 7], [7, 0], color='b', linestyle='--')

# Set aspect ratio to ensure square grid cells
ax.set_aspect("equal")

# Clip the circle using the diagonal line.
# This doesn't work
ax.set_clip_path(plt.Polygon([[0, 0], [7, 0], [0, 7]]))

# Show the plot
plt.title("Circle Centered at (0,0) (not) Clipped by Diagonal Line")
plt.show()

以下是它目前显示的内容.

enter image description here

我不想显示任何超过对角线的圆.

推荐答案

创建多边形时设置transform,并用circle.set_clip_path(polygon)剪裁圆.举个例子:

import matplotlib.pyplot as plt

# Create the circle with radius 6
circle = plt.Circle((0, 0), 6, color='r', fill=False)

# Set up the plot (reuse the previous grid settings)
plt.figure(figsize=(8, 8))
plt.xlim(0, 10)
plt.ylim(0, 10)
plt.grid()

# Add the circle to the plot
ax = plt.gca()
ax.add_patch(circle)

# Draw a diagonal line
plt.plot([0, 7], [7, 0], color='b', linestyle='--')

# Set aspect ratio to ensure square grid cells
ax.set_aspect("equal")

polygon = plt.Polygon([[0, 0], [7, 0], [0, 7]], transform=ax.transData)

# Clip the circle using the diagonal line.
circle.set_clip_path(polygon)

# Show the plot
plt.title("Circle Centered at (0,0) Clipped by Diagonal Line")
plt.show()

结果:

enter image description here

Python相关问答推荐

删除最后一个pip安装的包

需要计算60,000个坐标之间的距离

Python 约束无法解决n皇后之谜

为什么符号没有按顺序添加?

Pandas:将多级列名改为一级

我对我应该做什么以及我如何做感到困惑'

如何使用Python以编程方式判断和检索Angular网站的动态内容?

pandas:排序多级列

try 检索blob名称列表时出现错误填充错误""

如何在达到end_time时自动将状态字段从1更改为0

matplotlib + python foor loop

在二维NumPy数组中,如何 Select 内部数组的第一个和第二个元素?这可以通过索引来实现吗?

Pandas—堆栈多索引头,但不包括第一列

Python 3试图访问在线程调用中实例化的类的对象

Seaborn散点图使用多个不同的标记而不是点

Pandas:将值从一列移动到适当的列

在round函数中使用列值

对数据帧进行分组,并按组间等概率抽样n行

普洛特利express 发布的人口普查数据失败

Groupby并在组内比较单独行上的两个时间戳