pandas 如何根据条形图的值在 matplotlib 中创建自定义图例?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18974928/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create custom legend in matplotlib based on the value of the barplot?
提问by Santiago Munez
Supposedly, I have barplot as below:
据说,我有如下条形图:


The Day of Week 4 is for example refer to Wednesday, is it possible to create custom legend which indicate 4 - Wednesday?
例如,第 4 周的日期是指星期三,是否可以创建指示 4 - 星期三的自定义图例?
And also, if I have Day of Week, such as 3, and 4. 3 is for Tuesday. How possible to add another legend in the custom legend (3 - Tuesday) if only day of week 3 is displayed in the bar plot?
而且,如果我有星期几,例如 3 和 4。3 是星期二。如果条形图中仅显示第 3 周的第 3 天,如何在自定义图例(3 - 星期二)中添加另一个图例?
Thanks!
谢谢!
采纳答案by Joel Vroom
I wasn't entirely clear on what you wanted to accomplish but here may be one way of doing what you want:
我并不完全清楚你想要完成什么,但这里可能是做你想做的一种方式:
import matplotlib.pyplot as plt
daysofweek = {1:('Sunday','r'),
2:('Monday','g'),
3:('Tuesday','b'),
4:('Wednesday','yellow'),
5:('Thursday','k'),
6:('Friday', 'magenta'),
7:('Saturday', 'orange')}
ax1 = plt.subplot(111)
xval = [2., 4., 7.]
yval = [2.5, 3.6, 2.7]
for j in range(len(xval)):
ax1.bar(xval[j], yval[j], width=0.8, bottom=0.0, align='center', color=daysofweek[xval[j]][1], alpha=0.6, label=daysofweek[xval[j]][0])
ax1.set_xticks(xval)
ax1.set_xticklabels([daysofweek[i][0] for i in xval])
ax1.legend()
plt.show()
The result is:

结果是:

回答by PepeToro
Please add a working example so we know what is exactly what you want. Do the numbers come from somewhere? Anyhow, this program produces the attached figure. Maybe it will help you.
请添加一个工作示例,以便我们知道您想要什么。这些数字来自某个地方吗?总之,这个程序产生了附图。也许它会帮助你。


#Barplot
import matplotlib.pyplot as plt
import numpy as np
Day_names=["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
N=7
index = np.arange(N)
bar_width = 0.95
bar_height = [1,1.5,1.2,2,0.5,0.75,1]
bar_color = ['b','r','g','yellow','k', 'magenta', 'orange']
bars = plt.bar(index, bar_height, bar_width,alpha=0.5,color=bar_color)
plt.xlabel('Day')
plt.ylabel('Some Value')
plt.title('Bars')
plt.xticks(index + bar_width/2., Day_names)
plt.show()

