简体   繁体   English

Pandas 颜色条形图基于 dataframe 值

[英]Pandas color bar chart based off dataframe values

I'm still rather new to Pandas, and was unable to relate similar problems asked here with what I have.我对 Pandas 还是比较陌生,无法将此处提出的类似问题与我所拥有的联系起来。 I have 3 columns: country, mean, income stored in the dataframe.我有 3 列: country, mean, income存储在 dataframe 中。

I'm able to create a horizontal bar chart where countries as labeled on the Y axis, and the mean is listed on the X axis.我能够创建一个水平条形图,其中国家/地区在 Y 轴上标记,平均值列在 X 轴上。 The income field has 4 possible values, and I would like to color each bar based off those values.收入字段有 4 个可能的值,我想根据这些值为每个条着色。 I'm currently plotting with this and I am not sure how to use the income field to change the color of each bar depending on the income value我目前正在绘制这个,我不确定如何使用income字段根据收入值更改每个条形的颜色

df.sort_values(by=['mean']).plot.barh(x='country', y='mean')

From the docs , you can pass the optional argument color to barh()文档中,您可以将可选参数color传递给barh()

color: str, array-like, or dict, optional

with array-like being array-like存在

A sequence of color strings referred to by name, RGB or RGBA
code, which will be used for each column recursively....

So you can take your dataframe, create a list mapping each row in the plotted dataframe (including the sorting you do) to colors depending on the value of the income column and pass that as color argument.因此,您可以使用 dataframe,创建一个列表,将绘制的 dataframe 中的每一行(包括您所做的排序)映射到 colors,具体取决于income列的值并将其作为color参数传递。

Example: Sample dataframe示例:样本 dataframe

df = pd.DataFrame({'country': ["DE", "US"], 'mean': [0.1, 0.2] , 'income': ['value1', 'value2'] })
color_list = df.sort_values(by=['mean'])['income'].map('value1':'red', 'value2':'blue'}).tolist()

and

df.sort_values(by=['mean']).plot.barh(x='country', y='mean', color=color_list)

Output image Output 图片

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM