Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

enter image description hereFor visual effect purpose, I wish I could remove the grids outside the circle and only keep those are within the circle.

Btw, how to fulfill the cell ([8,9],[9,10]) with red color, I mean, the cell on the right of x=8 and down y=9.

My code is below and current image is also attached.

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)
like image 298
Jin Avatar asked Jul 31 '15 16:07

Jin


People also ask

How do I remove gridlines from a plot in Python?

Plot x and y points using the plot() method with linestyle, labels. To hide the grid, use plt. grid(False).

How do I get rid of gridlines in Seaborn?

To get rid of gridlines, use grid=False. To display the figure, use show() method.


1 Answers

The trick is to set the clip_path property on the gridline artists

Here's a simplified (minimal) example:

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()

Result:

enter image description here

like image 173
hitzg Avatar answered Sep 28 '22 08:09

hitzg