【发布时间】:2020-07-25 20:49:28
【问题描述】:
我尝试了多个代码来将条形图颜色调整为特定值。似乎颜色函数只检查索引中的第一项(在本例中为德国)并为索引中的所有其他项目设置条件。如果有人可以提供帮助,我将不胜感激:
colors = ['red' if 'Germany' else 'lightgrey' for x in first5_countries.index] #it colors all bars red
colors = ['r' if 'IT' else 'b' for index in first5_countries.index] #it colors everything red
colors = ['r' if pop_mln>85 else 'b' for pop_mln in first5_countries.pop_mln] #all bars blue
colors = ['r' if index=='Italy' else 'b' for index in first5_countries.index] #all bars blue
colors = ['b', 'b', 'b', 'r', 'b'] #yields blue
整个代码:
sorted_df = population_2019.sort_values(by='pop_mln', ascending=False)
first5_countries = sorted_df[:5]
colors = ['r' if index=='Italy' else 'b' for index in first5_countries.index]
first5_countries[['pop_mln']].plot.bar(figsize=(20,5), legend=False, color=colors)
plt.ylabel('Total population (in million)', size=12)
plt.xticks(rotation=30, ha='right')
plt.xlabel('')
plt.grid(axis='y')
plt.show()
first5_countries 的打印输出:
geo sex age year total_pop pop_mln
geo_full
Germany DE T TOTAL 2019 83019213.0 83.019213
France FR T TOTAL 2019 67012883.0 67.012883
United Kingdom UK T TOTAL 2019 66647112.0 66.647112
Italy IT T TOTAL 2019 60359546.0 60.359546
Spain ES T TOTAL 2019 46937060.0 46.937060
first5_countries.index.values
array(['德国', '法国', '英国', '意大利', '西班牙'], dtype=object)
【问题讨论】:
-
试试
color = ['lightgrey', 'lightgrey', 'lightgrey', 'red', 'lightgrey']。或者只是在之前创建一个颜色变量列表。 -
@SergeyDyshko 我尝试了这种方法,但它也不起作用 - 我将第一列指定为国家名称作为索引,并且在调用时似乎没有被拾取:(
标签: python matplotlib bar-chart