我想用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()
在生成的图形中,我希望图例中的误差条是水平的,而图形其余部分的误差线保持垂直。我希望这样,以便图例中的错误栏不会混淆数据点。我怎么能做到这一点?
答案 0 :(得分:0)
您可以从默认图例中检索误差条线对象,然后用它创建一个自定义图例,它会自动水平绘制,如下所示:
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()