如何在matplotlib中创建自定义的图例,基于barplot的值? [英] How to create custom legend in matplotlib based on the value of the barplot?

查看:676
本文介绍了如何在matplotlib中创建自定义的图例,基于barplot的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有barplot如下:

Supposedly, I have barplot as below:

第4周例如参考星期三,是否可以创建表示4 - 星期三的自定义图例?

The Day of Week 4 is for example refer to Wednesday, is it possible to create custom legend which indicate 4 - Wednesday?

如果我有星期几,如3和4. 3是星期二。

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?

谢谢!

推荐答案

我不完全清楚你想要完成什么,但这里可能是一种做你想要的方式:

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:

这篇关于如何在matplotlib中创建自定义的图例,基于barplot的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆