我正在写一个函数来使用matplotlib绘制直方图,我试图在mean, mean+2*sd, and mean-2*sd中添加垂直线。线条出现在图上,但我给它们的标签没有,你知道如何解决这个问题吗?
另外,我试图将此文本放入Mean = "for example x",但我使用的是硬编码的坐标plt.text(400, 0.015, "Mean = {}".format(round(mean, 3))),我如何使用编程方式来推断坐标的值?细线也是一样的:
plt.axis([min(data), max(data), 0, 0.02])我可以以一种更有效的方式获得最小和最大Y值,而不是硬编码吗?
def hist(location, data, mean, std, n_bins=20, x_label="", y_label="",
title=""):
samples = sorted(data)
x = np.linspace(min(samples), max(samples), 12)
y_pdf = stats.norm.pdf(x, mean, std)
y_skew_pdf = stats.skewnorm.pdf(x, *stats.skewnorm.fit(samples))
l1, = plt.plot(x, y_pdf, label='PDF')
l2, = plt.plot(x, y_skew_pdf, label='SKEW PDF')
# Compute histogram of Samples
n, bins, patches = plt.hist(samples, n_bins, density=True, facecolor='g', edgecolor='red', alpha=0.75)
plt.axvline(label='Mean', x=mean, linestyle=':', color='red')
plt.axvline(label='Mean-2*SD', x=round(mean-2*std, 3), linestyle='dashed')
plt.axvline(label='Mean+2SD', x=round(mean+2*std, 3), linestyle='dashed')
plt.xlabel(x_label)
plt.ylabel(y_label)
plt.title(title)
# The first plt.text arguments are coordinates x,y of the plot
plt.text(400, 0.015, "Mean = {}".format(round(mean, 3)))
plt.legend((l1, l2), (l1.get_label(), l2.get_label()), loc='upper right')
plt.axis([min(data), max(data), 0, 0.02])
plt.savefig(location)发布于 2019-03-21 03:55:57
将您的plt.legend(...行缩短为以下内容可能会有效:
plt.legend(loc='upper right');这对我很有效。我认为legend知道在哪里可以找到您在各个呼叫中指定的标签。对传说的明确可能导致它不去查找其余的内容。
此外,plot函数应该自动调整到您的数据的最小/最大值,这是我的经验。
https://stackoverflow.com/questions/52899633
复制相似问题