How to add a grid line at a specific location in m

2019-01-17 03:53发布

问题:

How do I add grid at a specific location on the y axis in a matplotlib plot?

回答1:

Yes. It's very simple. Use the set_[x|y]ticks methods of axes object and toggle the grid as normal:

import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.set_yticks([0.2, 0.6, 0.8], minor=False)
ax.set_yticks([0.3, 0.55, 0.7], minor=True)
ax.yaxis.grid(True, which='major')
ax.yaxis.grid(True, which='minor')
plt.show()



回答2:

If you only want to put in a line or two you can use

ax.axhline(y, linestyle='--', color='k') # horizontal lines
ax.axvline(x, linestyle='--', color='k') # vertical lines

with line style and color (or all the rest of line/artist properties) set to what ever you want