python - 图例中的顺序图 python

标签 python matplotlib plot

我需要在同一张图上绘制多组数据,我使用 matplotlib。

对于某些绘图,我使用 plt.plot(),对于其他绘图,我使用 plt.errorbar()。但是当我制作图例时,无论我以何种顺序将它们放入文件中,使用 plt.plot() 创建的图例首先出现(并且 zorder 似乎没有对图例中位置的影响)。

无论我如何绘制数据,如何在图例中给出我想要的顺序?

最佳答案

您可以手动调整顺序,方法是使用 ax.get_legend_handles_labels 获取图例句柄和标签,然后对生成的列表重新排序,并将它们提供给 ax.legend .像这样:

import matplotlib.pyplot as plt
import numpy as np

fig,ax = plt.subplots(1)

ax.plot(np.arange(5),np.arange(5),'bo-',label='plot1')
ax.errorbar(np.arange(5),np.arange(1,6),yerr=1,marker='s',color='g',label='errorbar')
ax.plot(np.arange(5),np.arange(2,7),'ro-',label='plot2')

handles,labels = ax.get_legend_handles_labels()

handles = [handles[0], handles[2], handles[1]]
labels = [labels[0], labels[2], labels[1]]

ax.legend(handles,labels,loc=2)
plt.show()

enter image description here

关于python - 图例中的顺序图 python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36866245/

相关文章:

python - 用于存储巨大(>5GB)排序文件的数据结构

python - 使用 matplotlib 运行线程会导致 python 崩溃

python - matplotlib.mlab.bivariate_normal 的等效函数

python - Matplotlib 散点图,每个 x 点有 2 个 y 点

r - 使用 ggplot 为手动添加的行添加图例

r - 当 y 轴不是 r 中的数字时,如何将文本分配给 ggplot

python - 如何测试一个字符串是否有大写字母

python - 组合回归模型中虚拟变量的影响

python - 在抓取大图像期间如何减少/限制带宽?

python - 如何绘制特征的变化