Python Matplotlib: 如何添加带有平均线精确值的图例

5

使用matplotlib库,我生成了一个包含两个直方图和均值线的图表。如果我添加图例,我认为图表会更清晰。我希望创建一个图例,说明这两条均值线的确切值。以下是我的代码、生成的图表和我想要实现的图片(在powerpoint中添加图例的图片):

def setPlot(data, mycolor, myalpha, mylinestyle):
    plt.style.use('ggplot')
    plt.rc('xtick',labelsize=12)
    plt.rc('ytick',labelsize=12)
    plt.xlabel("Incomes")
    plt.hist(data, bins=50, color= mycolor, alpha=myalpha)
    plt.axvline(numpy.mean(data), color=mycolor, linestyle=mylinestyle, linewidth=1.5)
    plt.show()

enter image description here

enter image description here

如果您对IT技术有任何建议,我将不胜感激。

-----------解决方案--------

由于wwiitom的伟大建议,我能够实现我的想法。我已经尝试了两个建议并将它们合并起来,这就是我得到的结果:

def setPlot(data, mycolor, myalpha, mylinestyle):
    plt.style.use('ggplot')
    plt.rc('xtick',labelsize=12)
    plt.rc('ytick',labelsize=12)
    plt.xlabel("Incomes")
    plt.hist(data, bins=50, color= mycolor, alpha=myalpha)
    plt.axvline(numpy.mean(data), color=mycolor, linestyle=mylinestyle, linewidth=1.5, label=str(numpy.mean(data)))
    plt.legend(loc='upper right')
    plt.show()

以下是我生成的绘图示例: enter image description here

非常感谢您的所有帮助!


1
你有没有浏览过 matplotlib 图库 - wwii
@wwii 谢谢,我一定会去看看,也许会找到一些有用的东西! - Ziva
2
将由axvline返回的Line2D对象分配给一个名称/变量。然后将其用作legend的参数 - 就像画廊中的示例一样。如果您找到了解决方案,请随时回答自己的问题。 - wwii
@wwii 非常感谢您的帮助!我已经学会了如何做,并改进了我的图表! - Ziva
1个回答

8

您只需要给您的axvline添加一个label,然后在绘制两个直方图之后调用plt.legend。像这样:

import matplotlib.pyplot as plt
import numpy

def setPlot(data, mycolor, myalpha, mylinestyle):
    plt.style.use('ggplot')
    plt.rc('xtick',labelsize=12)
    plt.rc('ytick',labelsize=12)
    plt.xlabel("Incomes")
    plt.hist(data, bins=50, color= mycolor, alpha=myalpha)
    plt.axvline(numpy.mean(data), color=mycolor, linestyle=mylinestyle,
                linewidth=1.5,label='{:5.0f}'.format(numpy.mean(data)))

setPlot(numpy.random.rand(100)*30000.,'r',0.5,'--')
setPlot(numpy.random.rand(100)*20000.,'b',0.5,'-')

plt.legend(loc=0)

plt.savefig('myfig.png')

enter image description here


谢谢你的回答,非常有帮助! - Ziva

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接