【问题标题】:How do you switch the colors of a bar chart in python matplotlib?如何在 python matplotlib 中切换条形图的颜色?
【发布时间】:2021-03-08 11:38:37
【问题描述】:

我正在尝试切换条形图的颜色,以便它们始终保持一致。在下面的图中,我想让 JP_Sales 在两个图表中都是橙色,而 NA_Sales 在两个图表中都是蓝色。

第一个图表的代码是:

Genre_sales.plot(kind= 'bar', rot=75, figsize = (15,10))
plt.suptitle('Sales by Region and Genre')
plt.ylabel('Total Units (Millions)')

第二张图表的代码是:

PercentSales.plot(kind = 'bar', rot = 80, figsize=(15,10))
plt.suptitle('Percentage by Genre Sales by Region')
plt.xlabel('Genre')
plt.ylabel('Percent')

【问题讨论】:

标签: python pandas matplotlib


【解决方案1】:

plot() 有一个 color 参数,它接受一个列表,您可以在其中按照条形出现的顺序指定颜色。所以你所要做的就是对每个情节进行以下更改:

#for Genre_sales if JP_sales is the first column and NA_sales is the second column:
Genre_sales.plot(kind = 'bar', rot = 75, color = ['orange', 'blue', 'green'], figsize = (15,10))

#for PercentSales if NA_sales is the first column and JP_sales is the second column:
PercentSales.plot(kind = 'bar', rot = 75, color = ['blue', 'orange', 'green', 'red'], figsize = (15,10))

【讨论】:

    【解决方案2】:

    你使用'set_color()'函数

    因此,在您的情况下,如果您想将其设置为红色,您将执行以下操作:

    Genre_sales.set_color('r')
    plt.show()
    

    同样:

    PercentSales.set_color('b')
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 2020-10-07
      • 2019-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-25
      相关资源
      最近更新 更多