【问题标题】:Specifying the order of matplotlib layers指定 matplotlib 层的顺序
【发布时间】:2016-09-11 19:56:47
【问题描述】:

假设我运行以下脚本:

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 为我挑选?

【问题讨论】:

  • 我看到 zorder 与它有关。但我仍然无法让它按我的意愿工作。如果我将蓝色、红色和绿色线的 zorder 分别设置为 0、1 和 2,则红色线是最上面的那条。为什么??

标签: python matplotlib plot layer


【解决方案1】:

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

为了解决您的问题,只需夸大zorder 中的差异即可。例如,不是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()

,结果如下:

对于这个情节,我指定了您问题中显示的相反顺序。

【解决方案2】:

图层从下到上按照相应调用绘图函数的顺序堆叠。

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规则排列的。

【讨论】:

  • 再补充一点,axes 也是这样堆叠在一个图上的。
  • 要添加这个,你可以设置ax.zorder来控制重叠的子图。这就是我需要的
【解决方案3】:

虽然 Tonechas 是正确的,默认顺序是根据调用绘图的顺序从后到前,但应该注意的是,使用其他绘图工具(散点图、误差条等)默认顺序并不那么明确.

import matplotlib.pyplot as plt
import numpy as np

plt.errorbar(np.arange(0,10),np.arange(5,6,0.1),color='r',lw='3')
plt.plot(np.arange(0,10),np.arange(0,10),'b', lw=3)

plt.show()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-11
    • 1970-01-01
    相关资源
    最近更新 更多