Matplotlib: keep grid lines behind the graph but the y and x axis above

前端 未结 4 683
孤街浪徒
孤街浪徒 2021-01-02 01:18

I am having a hard time plotting grid lines under my graphs without messing with the main x and y axis zorder:

import matplotlib.pyplot as plt
import numpy a         


        
4条回答
  •  梦谈多话
    2021-01-02 02:00

    I had the same problem of axes getting drawn below the plot line when I have grid lines in the background:

    ax.yaxis.grid()  # grid lines
    ax.set_axisbelow(True)  # grid lines are behind the rest
    

    The solution that worked for me was to set the zorder argument of the plot() function to a value between 1 and 2. It is not immediately clear, but the zorder value can be any number. From the documentation for the matplotlib.artist.Artist class:

    set_zorder(level)

    Set the zorder for the artist. Artists with lower zorder values are drawn first.

    ACCEPTS: any number

    Therefore:

    for i in range(5):
        ax.plot(range(10), np.random.randint(10, size=10), zorder=i / 100.0 + 1)
    

    I haven't checked for values outside this range, maybe they would also work.

提交回复
热议问题