Getting vertical gridlines to appear in line plot in matplotlib

前端 未结 6 1622
渐次进展
渐次进展 2020-12-01 05:41

I want to get both horizontal and vertical grid lines on my plot but only the horizontal grid lines are appearing by default. I am using a pandas.DataFrame from

6条回答
  •  离开以前
    2020-12-01 06:32

    Short answer (read below for more info):

    ax.grid(axis='both', which='both')
    

    What you do is correct and it should work.

    However, since the X axis in your example is a DateTime axis the Major tick-marks (most probably) are appearing only at the both ends of the X axis. The other visible tick-marks are Minor tick-marks.

    The ax.grid() method, by default, draws grid lines on Major tick-marks. Therefore, nothing appears in your plot.

    Use the code below to highlight the tick-marks. Majors will be Blue while Minors are Red.

    ax.tick_params(which='both', width=3)
    ax.tick_params(which='major', length=20, color='b')
    ax.tick_params(which='minor', length=10, color='r')
    

    Now to force the grid lines to be appear also on the Minor tick-marks, pass the which='minor' to the method:

    ax.grid(b=True, which='minor', axis='x', color='#000000', linestyle='--')
    

    or simply use which='both' to draw both Major and Minor grid lines. And this a more elegant grid line:

    ax.grid(b=True, which='minor', axis='both', color='#888888', linestyle='--')
    ax.grid(b=True, which='major', axis='both', color='#000000', linestyle='-')
    

提交回复
热议问题