Instead of grid lines in a plot, can matplotlib print grid grids?

I want to have some grid lines in the plot, but in fact the full-sized lines are too much / distracting, even the hatched light gray lines. I went and manually did some editing of the SVG output to get the effect I was looking for. Can this be done with matplotlib? I looked at the pyplot api for the grid, and the only thing I can see can be able to get closer to it are xdata and ydata Line2D kwargs.

enter image description here

+5
source share
2 answers

API, . " " , . :

import matplotlib.pyplot as plt

ax = plt.subplot(111)
ax.grid(clip_on=False, marker='o', markersize=10)
plt.savefig('crosses.png')
plt.show()

:

enter image description here

, 'o' , .

, , , Artists, -.

, :

import matplotlib.pyplot as plt
import numpy as np

NPOINTS=100

def set_grid_cross(ax, in_back=True):
    xticks = ax.get_xticks()
    yticks = ax.get_yticks()
    xgrid, ygrid = np.meshgrid(xticks, yticks)
    kywds = dict() 
    if in_back:
        kywds['zorder'] = 0
    grid_lines = ax.plot(xgrid, ygrid, 'k+', **kywds)

xvals = np.arange(NPOINTS)
yvals = np.random.random(NPOINTS) * NPOINTS

ax1 = plt.subplot(121)
ax2 = plt.subplot(122)

ax1.plot(xvals, yvals, linewidth=4)
ax1.plot(xvals, xvals, linewidth=7)
set_grid_cross(ax1)
ax2.plot(xvals, yvals, linewidth=4)
ax2.plot(xvals, xvals, linewidth=7)
set_grid_cross(ax2, in_back=False)

plt.savefig('gridpoints.png')
plt.show()

:

enter image description here

, x y, , ('+'). meshgrid, 1D 2 2D , . '+', ... . , , , . zorder , . *****

, , . , .

, x y, set_grid_cross, :

xticks = ax.get_xticks()[1:-1] #< notice the slicing
yticks = ax.get_yticks()[1:-1] #< notice the slicing
xgrid, ygrid = np.meshgrid(xticks, yticks)

, , , :

enter image description here

***** @fraxel .

+3

. , get_ticklocs() , , axhline axvline, . zorder=0, , . / . "gotchas"... , , xmin xmax, , .

import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(1,1,1)    
ax.plot((0,2,3,5,5,5,6,7,8,6,6,4,3,32,7,99), 'r-',linewidth=4)

x_ticks = ax.xaxis.get_ticklocs()
y_ticks = ax.yaxis.get_ticklocs()    
for yy in y_ticks[1:-1]:
    for xx in x_ticks[1:-1]:
        plt.axhline(y=yy, xmin=xx / max(x_ticks) - 0.02, 
                xmax=xx / max(x_ticks) + 0.02, color='gray', alpha=0.5, zorder=0)
        plt.axvline(x=xx, ymin=yy / max(y_ticks) - 0.02, 
                ymax=yy / max(y_ticks) + 0.02, color='gray', alpha=0.5, zorder=0)
plt.show()

enter image description here

+3

All Articles