首页 文章

指定matplotlib图层的顺序

提问于
浏览
14

假设我运行以下脚本:

import matplotlib.pyplot as plt

lineWidth = 20
plt.figure()
plt.plot([0,0],[-1,1], lw=lineWidth, c='b')
plt.plot([-1,1],[-1,1], lw=lineWidth, c='r')
plt.plot([-1,1],[1,-1], lw=lineWidth, c='g')
plt.show()

这产生以下结果:

如何指定图层的从上到下的顺序,而不是让我选择Python?

2 回答

  • 24

    这些层从底部到顶部以与绘图函数的相应调用相同的顺序堆叠 .

    import matplotlib.pyplot as plt
    
    lineWidth = 30
    plt.figure()
    
    plt.subplot(2, 1, 1)                               # upper plot
    plt.plot([-1, 1], [-1, 1], lw=5*lineWidth, c='b')  # bottom blue
    plt.plot([-1, 1], [-1, 1], lw=3*lineWidth, c='r')  # middle red
    plt.plot([-1, 1], [-1, 1], lw=lineWidth, c='g')    # top green
    
    plt.subplot(2, 1, 2)                               # lower plot
    plt.plot([-1, 1], [-1, 1], lw=5*lineWidth, c='g')  # bottom green
    plt.plot([-1, 1], [-1, 1], lw=3*lineWidth, c='r')  # middle red
    plt.plot([-1, 1], [-1, 1], lw=lineWidth, c='b')    # top blue
    
    plt.show()
    

    从下图中可以清楚地看出,这些图是根据 bottom first, top last 规则排列的 .

  • 2

    我不知道为什么 zorder 有这种行为,而且很可能是一个错误,或者至少是一个记录错误的特征 . 这可能是因为在构建绘图(如网格,轴等等)时已经自动引用 zorder ,当您尝试为元素指定 zorder 时,您会以某种方式重叠它们 . 无论如何,这是假设的 .

    为了解决您的问题,只需在_35787中夸大其差异即可 . 例如,而不是 0,1,2 ,使其成为 0,5,10

    import matplotlib.pyplot as plt
    
    lineWidth = 20
    plt.figure()
    plt.plot([0,0],[-1,1], lw=lineWidth, c='b',zorder=10)
    plt.plot([-1,1],[-1,1], lw=lineWidth, c='r',zorder=5)
    plt.plot([-1,1],[1,-1], lw=lineWidth, c='g',zorder=0)
    plt.show()
    

    ,结果如下:

    对于这个图,我指定了你问题中显示的相反顺序 .

相关问题