【问题标题】:How to put colors in a matplotlib bar chart?如何在 matplotlib 条形图中添加颜色?
【发布时间】:2019-09-26 17:16:11
【问题描述】:

我正在尝试为下面图表的每个条形上色。我需要放置可以手动设置每个条形的特定颜色。

我已经尝试过使用: #Attempt 1

colors = ['cyan', 'lightblue', 'lightgreen', 'tan','blue']

for patch, color in zip (bar_plot ['boxes'], colors):
    patch.set_facecolor (color)

尝试 1-> 导致错误的原因:“AxesSubplot”对象不可下标

#Attempt 2

colors = ['#1b9e77', '#a9f971', '#fdaa48','#6890F0','#A890F0']

ax1 = dfPoputationResident.plot('Zona','Total_MSP', kind = 'bar', color = colors);

尝试 2 的结果->这不起作用,所有条形都是颜色 '# 1b9e77',而不是散布,每个条形都采用一种颜色。

我相信这是因为我的数据框是之前合并的结果。

所以在制作图表之前我重置了索引。

dfPoputationResident = dfPoputationResident.reset_index () 这是reset_index后的dataframe

然后我做了:

ax1 = dfPoputationResident.plot ('Zone', 'Total_MSP', kind = 'bar');

但即使在重置索引之后,当我这样做时

dfPoputationResident.columns
MultiIndex (levels = [['Total_MSP', 'Zone'], ['sum', '']],
           codes = [[1,0], [1,0]])

考虑到这些特征,如何制作条形图并在每个条形上放置特定颜色?请帮帮我。我是 Python 新手。

谢谢!

【问题讨论】:

    标签: python pandas matplotlib


    【解决方案1】:

    可能是因为您的数据框是多索引列。试试:

    dfPoputationResident.columns = ['Zona', 'Total_MSP']
    

    你可以做的另一件事是当你groupby创建dfPoputationResident时,你可以这样做:

    dfPoputationResident = df.groupby('Zona')['Total_MSP'].sum()
    

    而不是

    dfPoputationResident = df.groupby('Zona')[['Total_MSP']].sum()
    

    我的意思是,这对我有用:

    df = pd.DataFrame({'Zona':list('abcde'),
                       'Total_MSP':[1,2,3,4,5]})
    
    fig, ax = plt.subplots()
    
    colors = ['#1b9e77', '#a9f971', '#fdaa48','#6890F0','#A890F0']
    df.plot.bar(x='Zona',y='Total_MSP',color=colors, ax=ax);
    
    ax.legend(ax.patches, df['Zona'], loc=[1.01,0.5])
    

    输出:

    【讨论】:

    • 太棒了!非常感谢你再次拯救了我的一天!我希望有一天我可以报答你。
    【解决方案2】:

    按照 Quang Hoang 提出的 suluction 遵循我的代码:

    dfPoputationResident.columns = ['Zona', 'Total_MSP']
    
    dfPoputationResident = dfPoputationResident.groupby('Zona')['Total_MSP'].sum()
    
    df = pd.DataFrame({'Zona':list('abcde'),
                       'Total_MSP':[dfPoputationResident.iloc[0],dfPoputationResident.iloc[1],dfPoputationResident.iloc[2],dfPoputationResident.iloc[3],dfPoputationResident.iloc[4]]})
    
    colors = ['#1b9e77', '#a9f971', '#fdaa48','#6890F0','#A890F0']
    df.plot.bar(x='Zona',y='Total_MSP',color=colors)
    
    
    #change the name of month on the x 
    ax = plt.gca()
    names= ['Centro', 'Leste', 'Norte', 'Oeste', 'Sul']   
    ax.set_xticklabels(names)
    
    x = plt.gca().xaxis
    
    # rotate the tick labels for the x axis
    for item in x.get_ticklabels():
        item.set_rotation(0)    
    
    for spine in plt.gca().spines.values():
        spine.set_visible(False)
    plt.show()
    

    enter image description here

    【讨论】:

    • 这太过分了。你可以在dfPoputationResident = dfPoputationResident.groupby('Zona')['Total_MSP'].sum()之后做dfPoputationResident .plot.bar(color=colors)
    猜你喜欢
    • 2020-10-07
    • 2013-10-23
    • 1970-01-01
    • 2019-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-25
    相关资源
    最近更新 更多