Python Plot:如何删除不在圆圈内的网格线?

时间:2015-07-31 16:34:57

标签: 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)

1 个答案:

答案 0 :(得分:4)

诀窍是在网格线艺术家

上设置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