【问题标题】:plot data from pandas DataFrame, colour dependent on column value绘制来自 pandas DataFrame 的数据,颜色取决于列值
【发布时间】: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

population

first5_countries.index.values

array(['德国', '法国', '英国', '意大利', '西班牙'], dtype=object)

【问题讨论】:

  • 试试color = ['lightgrey', 'lightgrey', 'lightgrey', 'red', 'lightgrey']。或者只是在之前创建一个颜色变量列表。
  • @SergeyDyshko 我尝试了这种方法,但它也不起作用 - 我将第一列指定为国家名称作为索引,并且在调用时似乎没有被拾取:(

标签: python matplotlib bar-chart


【解决方案1】:

您可以像这样定义您的colors

colors = ['red' if x=='Italy' else 'lightgray' for x in first5_countries.index]

然后传递给绘图函数:

first5_countries['population_mln'].plot.bar(figsize=(20,5),color=colors, legend=False)

你们会一起做:

colors = ['red' if x=='Italy' else 'lightgray' for x in first5_countries.index]

first5_countries['pop_mln'].plot.bar(figsize=(20,5),color=colors, legend=False)

输出会是这样的:

【讨论】:

  • 这很有用,谢谢,但该功能似乎没有选择国家名称意大利(也没有任何其他)。该函数做了一些奇怪的事情,例如。 colors = ['red' if x=='Germany' else 'yellow' for x in first5_countries.index] 以红色返回每个条,而 colors = ['lightgrey' if x=='Italy' else 'yellow' for x in first5_countries.index] 以黄色返回所有内容
  • first5_countries.index 替换为first5_countries['country_col'],其中country_col 是您所在国家/地区列的名称。
  • 不幸的是,列名“geo_full”未被识别,我之前将该列设置为索引列 demo_pjangroup = demo_pjangroup.set_index('geo_full') - 该列包括所有国家/地区名称
  • 它也不适用于任何其他条件,例如。 colors = ['lightgrey' if x>60 else 'red' for x in first5_countries['population_mln']]
  • @Magdalena 你能用first5_countries的打印输出更新你的帖子吗?
猜你喜欢
  • 2018-09-15
  • 2018-04-16
  • 2020-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多