gpt4 book ai didi

Python Matplotlib : add legend with the exact value of a mean lien

转载 作者:行者123 更新时间:2023-12-05 00:22:15 44 4
gpt4 key购买 nike

我使用 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

我将不胜感激任何建议。

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

感谢 的伟大建议二战 汤姆我能够实现我的想法的解决方案。我试图连接这两个建议,这就是我得到的:
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

非常感谢您的帮助!

最佳答案

你只需要给你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

关于Python Matplotlib : add legend with the exact value of a mean lien,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30281547/

44 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com