【问题标题】:How can I make legend error bars horizontal in matplotlib如何在 matplotlib 中使图例误差线水平
【发布时间】:2015-03-06 01:11:33
【问题描述】:

我想用 matplotlib 制作一个图表,其中图表中的误差线是垂直的, 但是图例中的误差线是水平的。示例代码(如下)产生一个 图例中的误差线是垂直的。 如何使图例错误栏水平?

代码:

import numpy as np  
import matplotlib.pyplot as plt    
x = np.linspace(0, 2*np.pi, 6)  
y = np.sin(x)  
dy = 0.1*np.abs(y)  
plt.errorbar(x, y, yerr = dy, label="data", fmt='o')  
plt.legend(loc="upperright", numpoints=1, frameon=False)  
plt.show()  

在生成的图表中,我希望图例中的误差条是水平的,而图表其余部分的误差条保持垂直。我想要这样,以便图例中的错误栏不会与数据点混淆。我怎样才能做到这一点?

【问题讨论】:

  • 您的主要问题是哪一个?您应该将每个问题作为个人发布。
  • 不混淆数据点的最简单方法就是保持图例框架处于打开状态......
  • matplotlib.org/users/legend_guide.html 它不像它应该的那样严格,但你可以为艺术家类注册任意处理程序。

标签: python matplotlib


【解决方案1】:

您可以从默认图例中检索误差线对象,然后使用它创建自定义图例,它将自动水平绘制,如下所示:

import numpy as np                 # v 1.19.2
import matplotlib.pyplot as plt    # v 3.3.2

x = np.linspace(0, 2*np.pi, 6)  
y = np.sin(x)  
dy = 0.1*np.abs(y)

fig, ax = plt.subplots()
plt.errorbar(x, y, yerr=dy, label='data', fmt='o', ecolor='red')

# Retrieve handles and labels: note the tuple within the tuple to
# unpack the handles
(errorbar_container,), labels = ax.get_legend_handles_labels()
point, line = errorbar_container.get_children()

# Create the custom legend: note that the handles are drawn on top of
# one another in the order that they are listed in the tuple
plt.legend([(line, point)], labels, frameon=False)

plt.show()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-05
    • 2013-11-09
    • 1970-01-01
    • 1970-01-01
    • 2021-03-03
    • 2014-01-29
    相关资源
    最近更新 更多