If you simply display the grid with grid ()
in matplotlib
It only draws a line where the scale is displayed
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 2 * 100 + 1)
f = sin(x)
plt.rc('font', family='serif')
plt.figure()
plt.ylim([-1.5, 1.5])
plt.plot(f, color='black')
plt.grid()
plt.show()
Suppose you want to add 5 lines on the x-axis and 0.1 lines on the y-axis to this graph.
Since grid "draws a line where the scale is displayed", try increasing the scale using xticks
and yticks
.
plt.rc('font', family='serif')
plt.figure()
plt.ylim([-1.5, 1.5])
plt.plot(f, color='black')
#Scale display in 5 increments
plt.xticks(list(filter(lambda x: x%5==0, np.arange(201))))
# 0.Scale display in 1 increments
plt.yticks(list(map(lambda y: y*0.1, np.arange(-15,15))))
plt.grid()
plt.show()
Although it is displayed like this, the value display on the scale is terribly difficult to see.
In the first place, matplotlib scales have large and small scales, and the value of the scale is displayed only on the large scale.
Since xticks
and yticks
were operating the display of the large scale,
This time, by manipulating the display of the small scale with set_minor_locator
Realize "turn off the scale while leaving the grid"
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as tick #Load the library required for scale operation
x = np.arange(0, 2 * 100 + 1)
f = sin(x)
plt.rc('font', family='serif')
plt.figure()
plt.ylim([-1.5, 1.5])
plt.plot(f, color='black')
#Small scale in 5 increments on x-axis(minor locator)display
plt.gca().xaxis.set_minor_locator(tick.MultipleLocator(5))
#0 on y axis.Small scale in 1 increments(minor locator)display
plt.gca().yaxis.set_minor_locator(tick.MultipleLocator(0.1))
#Grid display for small scales
plt.grid(which='minor')
plt.show()
In this way, the grid can be displayed in small steps, while the scale part can be refreshed.
Recommended Posts