LiamNeesonFan
LiamNeesonFan

Reputation: 2823

How do I draw a grid onto a plot in Python?

I just finished writing code to make a plot using pylab in Python and now I would like to superimpose a grid of 10x10 onto the scatter plot. How do I do that?

My current code is the following:

x = numpy.arange(0, 1, 0.05)
y = numpy.power(x, 2)

fig = plt.figure()
ax = fig.gca()
ax.set_xticks(numpy.arange(0, 1, 0.1))
ax.set_yticks(numpy.arange(0, 1., 0.1))
plt.scatter(x, y)
plt.show()

And its output is:

Without grid

What I would like is the following output:

With grid

Upvotes: 250

Views: 701596

Answers (5)

cottontail
cottontail

Reputation: 23509

If you want more gridlines than the ticklabels, you can do so using minor ticks. Essentially, the basic idea is to draw gridlines for minor ticks, too. The following is an example where more grid lines than tick labels are draw.

import matplotlib.pyplot as plt

x = np.arange(0, 1, 0.05)
y = x**2

plt.scatter(x, y)
plt.xticks(np.arange(0, 1.01, 0.2))
plt.yticks(np.arange(0, 1.01, 0.2));

plt.xticks(np.arange(0, 1, 0.1), minor=True)   # set minor ticks on x-axis
plt.yticks(np.arange(0, 1, 0.1), minor=True)   # set minor ticks on y-axis
plt.tick_params(which='minor', length=0)       # remove minor tick lines

plt.grid()                                     # draw grid for major ticks
plt.grid(which='minor', alpha=0.3)             # draw grid for minor ticks on x-axis

img1


If you want fewer grid lines than tick labels (perhaps to mark landmark points such as first day of each month in a time-series etc.), one way is to draw gridlines using major tick positions but only show minor ticks. The following is an example that shows a grid line on the x-axis for every 3rd tick position.

plt.scatter(x, y)
plt.xticks(np.arange(0, 1.01, 0.3))   # set major x-ticks
plt.yticks(np.arange(0, 1.01, 0.1))   # set major y-ticks

# set minor x-ticks
plt.xticks(np.arange(0, 1.01, 0.1), np.arange(0, 1.01, 0.1).round(1), minor=True)

# make the minor x-ticks have the same properties as the major ticks
# (this effectively overwrites the major ticks with the minor ones)
ax = plt.gca()
plt.tick_params(
    axis='x',
    which='minor', 
    pad=ax.xaxis.get_tick_padding(), 
    length=ax.xaxis.get_majorticklines()[0].get_markersize(), 
    width=ax.xaxis.get_majorticklines()[0].get_markeredgewidth())

# draw x-axis gridlines at major tick positions
plt.grid(axis='x')

If the grid lines are few, a much easier approach to do the same thing is to plot vertical (axvline) or horizontal lines (axhline) on the desired points.

plt.scatter(x, y)
plt.xticks(np.arange(0, 1.01, 0.1))
plt.yticks(np.arange(0, 1.01, 0.1))

# draw grid for every third point
for pt in np.arange(0, 1.01, 0.3):
    plt.axvline(pt, lw=0.5, color='black', alpha=0.5)

img2

Upvotes: 3

Ani
Ani

Reputation: 2988

Using rcParams you can show grid very easily as follows

plt.rcParams['axes.facecolor'] = 'white'
plt.rcParams['axes.edgecolor'] = 'white'
plt.rcParams['axes.grid'] = True
plt.rcParams['grid.alpha'] = 1
plt.rcParams['grid.color'] = "#cccccc"

If grid is not showing even after changing these parameters then use

plt.grid(True)

before calling

plt.show()

Upvotes: 37

Jossef Harush Kadouri
Jossef Harush Kadouri

Reputation: 34277

To show a grid line on every tick, add

plt.grid(True)

For example:

import matplotlib.pyplot as plt

points = [
    (0, 10),
    (10, 20),
    (20, 40),
    (60, 100),
]

x = list(map(lambda x: x[0], points))
y = list(map(lambda x: x[1], points))

plt.scatter(x, y)
plt.grid(True)

plt.show()

enter image description here


In addition, you might want to customize the styling (e.g. solid line instead of dashed line), add:

plt.rc('grid', linestyle="-", color='black')

For example:

import matplotlib.pyplot as plt

points = [
    (0, 10),
    (10, 20),
    (20, 40),
    (60, 100),
]

x = list(map(lambda x: x[0], points))
y = list(map(lambda x: x[1], points))

plt.rc('grid', linestyle="-", color='black')
plt.scatter(x, y)
plt.grid(True)

plt.show()

enter image description here

Upvotes: 93

Andrey Sobolev
Andrey Sobolev

Reputation: 12713

You want to use pyplot.grid:

x = numpy.arange(0, 1, 0.05)
y = numpy.power(x, 2)

fig = plt.figure()
ax = fig.gca()
ax.set_xticks(numpy.arange(0, 1, 0.1))
ax.set_yticks(numpy.arange(0, 1., 0.1))
plt.scatter(x, y)
plt.grid()
plt.show()

ax.xaxis.grid and ax.yaxis.grid can control grid lines properties.

Enter image description here

Upvotes: 304

oxidworks
oxidworks

Reputation: 1642

Here is a small example how to add a matplotlib grid in Gtk3 with Python 2 (not working in Python 3):

#!/usr/bin/env python
#-*- coding: utf-8 -*-

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
from matplotlib.figure import Figure
from matplotlib.backends.backend_gtk3agg import FigureCanvasGTK3Agg as FigureCanvas

win = Gtk.Window()
win.connect("delete-event", Gtk.main_quit)
win.set_title("Embedding in GTK3")

f = Figure(figsize=(1, 1), dpi=100)
ax = f.add_subplot(111)
ax.grid()

canvas = FigureCanvas(f)
canvas.set_size_request(400, 400)
win.add(canvas)

win.show_all()
Gtk.main()

enter image description here

Upvotes: 4

Related Questions