Python 情节 : How to remove grid lines not within the circle?

标签 python matplotlib

enter image description here出于视觉效果的目的,我希望我可以删除圆圈外的网格,只保留圆圈内的网格。

顺便说一句,如何用红色填充单元格 ([8,9],[9,10]),我的意思是,x=8 右侧和 y=9 下方的单元格。

我的代码在下面,还附上了当前图片。

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.transforms import BlendedGenericTransform

fig, ax = plt.subplots()

ax.text(0, -0.02, 'y', transform=BlendedGenericTransform(ax.transData, ax.transAxes), ha='center')
ax.text(1.01, 0, 'x', transform=BlendedGenericTransform(ax.transAxes, ax.transData), va='center')

ax.set_xticks(np.arange(0,side+1,1))
ax.set_yticks(np.arange(0,side+1,1))
plt.grid()

ax.xaxis.tick_top()
plt.gca().invert_yaxis()

circle = plt.Circle((15, 15), radius=15, fc='w')
plt.gca().add_patch(circle)

fig.set_size_inches(18.5, 10.5)

最佳答案

诀窍是在网格线艺术家上设置 clip_path 属性

这是一个简化的(最小的)示例:

import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

# draw the circle
circle = plt.Circle((15, 15), radius=15, fc='w')
ax.add_patch(circle)

# settings for the axes
ax.grid()
ax.set_xlim(0,30)
ax.set_ylim(0,30)
ax.set_aspect(1)

# clip the gridlines
plt.setp(ax.xaxis.get_gridlines(), clip_path=circle)
plt.setp(ax.yaxis.get_gridlines(), clip_path=circle)

plt.show()

结果:

enter image description here

关于Python 情节 : How to remove grid lines not within the circle?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31751036/

相关文章:

python - 描述中的 Matplotlib tex-macro

python - 线程 - 如何获取父 ID/名称?

python - pylab 和 pyplot 有什么区别?

python - 如何避免 numpy 数组中的 'for' 循环

matplotlib - matplotlib 的 axvline 中的错误?

python - 在列表列表中绘制点的快速方法

python - CPU 上的 tensorflow-mkl 问题

python - Pandas MultiIndex 分层列的选择

python - 付款时出现 HTTP 400

Python:忽略 xml.etree.ElementTree 中的 namespace ?