How to draw a grid on a plot in Python?

I just finished writing code to make a plot using pylab in Python, and now I would like to overlay a 10x10 grid on the scatter plot. How to do it?

+128
python matplotlib
Nov 21 '11 at 9:18
source share
5 answers

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 the properties of grid lines.

Enter image description here

+175
Nov 21 '11 at 11:00
source share

To show the grid line at each 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 can customize the style (for example, a solid line instead of a 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

+34
Jun 18 '16 at 12:00
source share
+9
Nov 21 '11 at 11:03
source share

Using rcParams, you can very easily display the grid 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 the grid does not appear even after changing these settings, use

 plt.grid(True) 

before the call

 plt.show() 
+6
Mar 24 '17 at 7:28
source share

Here is a small example of how to add a matplotlib grid in Gtk3 with Python 2 (doesn't work 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

+1
03 Oct '16 at 12:27
source share



All Articles