在图例中绘制代表性的误差条大小?
我有一些数据(里面有错误),需要在一个比较密集的图表中展示。我想把这些点画出来,但不想加误差条(因为这样看起来太复杂了),而是想在图例中画一个代表性的误差条(显示准确的误差大小)。
这是我目前的尝试(但没有成功)。
import pylab as pl
p1, = pl.plot([1,2,3], label="test1")
p2, = pl.plot([3,2,1], label="test2")
errorbarsize = 1.65 # Need this to be properly scaled in the legend
# p3, = pl.plot([1], label='data', color="red") # works
# p3, = pl.scatter(1, 1, label='data', color="red")
# p3, = pl.errorbar(1, 1, yerr=errorbarsize, label='data', color="red")
l1 = pl.legend([p1], ["Label 1"], loc=1)
l2 = pl.legend([p2], ["Label 2"], loc=2) # this removes l1 from the axes.
l3 = pl.legend([p3], ["Label 3"], loc=3, numpoints=1)
gca().add_artist(l1) # add l1 as a separate artist to the axes
gca().add_artist(l2) # add l2 as a separate artist to the axes
另外,如果我能把这个误差条放在一个单独的图例里,那就更好了,不过这可能有点难。
1 个回答
0
这里有一个例子,使用了Thorsten Kranz的建议,还有另一个例子展示了如何显示代表性的误差条...
import matplotlib.pyplot as plt
import numpy as np
fig, axs = plt.subplots(2,1)
# -- make some fake data
x = np.random.normal(loc=4, size=100)
x.sort()
y = np.random.normal(loc=5, size=100)
y.sort()
y_errorbarsize = y.std()
x_errorbarsize = y.std()
### Example 1
# From Thorsten Kranz comment...
axs[0].plot(x, y, label="Example #1")
axs[0].fill_between(x,y-y_errorbarsize/2, y+y_errorbarsize/2,alpha=0.3)
### Example 2
axs[1].scatter(x, y, label="Example #2", alpha=0.8)
# Place our representative error bar by hand.
axis_coordinates_of_representative_error_bar = (0.1, 0.8)
screen_coordinates_of_representative_error_bar = axs[1].transAxes.transform(axis_coordinates_of_representative_error_bar)
screen_to_data_transform = axs[1].transData.inverted().transform
data_coordinates_of_representative_error_bar = screen_to_data_transform(screen_coordinates_of_representative_error_bar)
foo = data_coordinates_of_representative_error_bar
axs[1].errorbar(foo[0], foo[1], xerr=x_errorbarsize/2, yerr=y_errorbarsize/2, capsize=3)
plt.show()
plt.close()