Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Matplotlib Grid Lines

Matplotlib Grid Lines

We can use the grid() method in pyplot to set the grid lines in a chart.

The syntax of the grid() method is as follows:


matplotlib.pyplot.grid(b=None, which='major', axis='both', )

Parameter Description:

The following example adds a simple grid line using the default parameter values:

Example

import

numpy

as

np

import

matplotlib.

pyplot

as

plt

x

=

np.

array

(

[

1

,

2

,

3

,

4

]

)

y

=

np.

array

(

[

1

,

4

,

9

,

16

]

)

plt.

title

(

"RUNOOB grid() Test"

)

plt.

xlabel

(

"x - label"

)

plt.

ylabel

(

"y - label"

)

plt.

plot

(

x

,

y

)

plt.

grid

(

)

plt.

show

(

)

The display result is as follows:

The following example adds a simple grid line with the axis parameter set to x, showing grid lines along the x-axis:

Example

import

numpy

as

np

import

matplotlib.

pyplot

as

plt

x

=

np.

array

(

[

1

,

2

,

3

,

4

]

)

y

=

np.

array

(

[

1

,

4

,

9

,

16

]

)

plt.

title

(

"RUNOOB grid() Test"

)

plt.

xlabel

(

"x - label"

)

plt.

ylabel

(

"y - label"

)

plt.

plot

(

x

,

y

)

plt.

grid

(

axis

=

'x'

)

Set y to show grid lines along that axis direction

plt.

show

(

)

The display result is as follows:

The following example adds a simple grid line and sets the style of the grid lines, in the following format:

grid(color = 'color', linestyle = 'linestyle', linewidth = number)

Parameter Description:

color:'b' blue, 'm' magenta, 'g' green, 'y' yellow, 'r' red, 'k' black, 'w' white, 'c' cyan, '#008000' RGB color string.

linestyle:'‐' solid line, '‐‐' dashed line, '‐.' dash-dot line, ':' dotted line.

linewidth: Sets the line width; can be set to a number.

Example

import

numpy

as

np

import

matplotlib.

pyplot

as

plt

x

=

np.

array

(

[

1

,

2

,

3

,

4

]

)

y

=

np.

array

(

[

1

,

4

,

9

,

16

]

)

plt.

title

(

"RUNOOB grid() Test"

)

plt.

xlabel

(

"x - label"

)

plt.

ylabel

(

"y - label"

)

plt.

plot

(

x

,

y

)

plt.

grid

(

color

=

'r'

,

linestyle

=

'--'

,

linewidth

=

0.5

)

plt.

show

(

)

The display result is as follows: