出于视觉效果的目的,我希望我可以删除圆圈外的网格,只保留圆圈内的网格。
顺便说一句,如何用红色填充单元格 ([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()
结果:
关于Python 情节 : How to remove grid lines not within the circle?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31751036/