Python 熊猫数据框的绘图数据,颜色取决于列值

Python 熊猫数据框的绘图数据,颜色取决于列值,python,matplotlib,bar-chart,Python,Matplotlib,Bar Chart,我尝试了多种代码,将条形图颜色设置为特定值。颜色函数似乎只检查索引中的第一项(在本例中为德国),并为索引中的所有其他项设置条件。如果有人能帮助我,我将不胜感激: 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

我尝试了多种代码,将条形图颜色设置为特定值。颜色函数似乎只检查索引中的第一项(在本例中为德国),并为索引中的所有其他项设置条件。如果有人能帮助我,我将不胜感激:

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()
前5个国家/地区的打印输出:

    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

数组([“德国”、“法国”、“英国”、“意大利”、“西班牙”],
dtype=object)

您可以这样定义您的
颜色

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=='Italy' else 'lightgray' for x in first5_countries.index]

试试
color=[“浅灰色”、“浅灰色”、“浅灰色”、“红色”、“浅灰色”]
。或者之前只是创建一个颜色变量列表。@SergeyDyshko我尝试过这个方法,但也不起作用-我给第一列指定了国家名称作为索引,调用时它似乎没有被拾取:(这很有用,谢谢,但函数似乎没有拾取国家名称Italy(或任何其他名称)。该函数会执行一些奇怪的操作,例如: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
with
first5_countries['country\col']
其中
country\u col
是您所在国家/地区列的名称。不幸的是,列名“geo\u full”无法识别,我以前使用demo\u pjangroup=demo\u pjangroup将该列设置为索引列。set\u index('geo\u full')-该列包括所有国家/地区名称它也不适用于任何其他条件,例如颜色=['lightgrey'如果x>60,其他'red'表示前5个国家的x['population\mln']@Magdalena你能用
前5个国家的打印件更新你的帖子吗?