【问题标题】:coloring bar charts in matplotlib depending on dcitionary key value根据字典键值在matplotlib中着色条形图
【发布时间】:2020-11-24 00:18:47
【问题描述】:

我有一本设备及其电池电量的字典,我在这里要做的是绘制直方图,用颜色显示电池电量,如果电池电量低于 20 则为红色,2060

我正在使用 matplotlib、pyplot 并且我试图迭代我的​​字典中的键值,但我在我的 for 循环中遇到语法错误(我可以循环键并为每个条设置颜色值吗?),我'不知道我做错了什么,这是我的代码:

import matplotlib.pyplot as plt

dic={'Door1':50,'Hall':20,'Garage':90,'Door101':15}


i=0
for i in dic.keys()
    if dic.keys(i) <20:
        color='r'
    if 20<dic.keys(i) >=60 
        color='y'
    if dic.keys(i) >=90
        color='g
    i=i+1


plt.bar(range(len(dic)), list(dic.values()), align='center' , color=color)  
plt.xticks(range(len(dic)), list(dic.keys())) 

plt.title('Battery Level')
#save my plot as a png file to insert in Ifram html later
plt.savefig('my_plot.png')

【问题讨论】:

    标签: python pandas matplotlib colors bar-chart


    【解决方案1】:

    我认为这是您想要的解决方案:

    import matplotlib.pyplot as plt
    
    dic = {'Door1': 50, 'Hall': 20, 'Garage': 90, 'Door101': 15}
    
    color = []
    
    for i in dic.keys():
        if dic[i] < 20:
            color.append('red')
        if 20 <= dic[i] <= 60:
            color.append('yellow')
        if dic[i] >= 90:
            color.append('green')
    
    plt.bar(range(len(dic)), list(dic.values()), align='center', color=color)
    plt.xticks(range(len(dic)), list(dic.keys())) 
    
    plt.title('Battery Level')
    # save my plot as a png file to insert in Ifram html later
    plt.savefig('my_plot.png')
    

    输出:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-15
      • 2022-01-10
      • 2015-12-03
      • 2014-01-21
      • 2018-09-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多