[英]How can I make legend error bars horizontal in matplotlib
我想用 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()
在生成的图表中,我希望图例内的误差条是水平的,而图表其余部分的误差条保持垂直。 我想要这样,以便图例中的误差条不会与数据点混淆。 我怎样才能做到这一点?
您可以从默认图例中检索误差条线对象,然后用它创建一个自定义图例,它会自动水平绘制,如下所示:
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.