pandas 图自动为类别分配颜色 [英] pandas plot automatically assigning color to categories

查看:40
本文介绍了 pandas 图自动为类别分配颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对我的数据框绘制条形图,以便分类列 ('ad') 定义条形图的颜色.这是我的数据:

I want to do a bar plot my dataframe such that the categorical column ('ad') defines the colors of my bar charts. This is my data:

"date","shown","clicked","converted","avg_cost_per_click","total_revenue","ad"
2015-10-01,65877,2339,43,0.9,641.62,"ad_group_1"
2015-10-02,65100,2498,38,0.94,756.37,"ad_group_1"
2015-10-03,70658,2313,49,0.86,970.9,"ad_group_2"
2015-10-04,69809,2833,51,1.01,907.39,"ad_group_2"
2015-10-05,68186,2696,41,1,879.45,"ad_group_3"
2015-10-06,66864,2617,46,0.98,746.48,"ad_group_3"
2015-10-07,68227,2390,42,0.94,462.33,"ad_group_4"
2015-10-08,68520,2909,46,1.07,441.28,"ad_group_4"
2015-10-09,67250,2385,49,0.88,602.14,"ad_group_5"

我最多有40个广告组.

i have up to 40 ad groups.

我的代码:

columns=['date','converted','clicked','ad']
df2=pd.DataFrame(df,columns=columns)
df2.set_index(df2.date,inplace=True)

在这里,我只用1列(单击")相对于日期"进行绘制

here i take only 1 column ('clicked') to plot against 'date'

plt.figure()
df2.loc[:,['clicked','ad']].plot(kind='bar')
plt.show()
#df2.loc[:,['clicked','ad']].plot(kind='bar',colormap='ad')

带有 colormap 的代码行不起作用,因为我没有颜色列表.我已经看到了用户手动创建类别到颜色的颜色映射的答案.我有 40 多个类别,无法手动完成.

The line of code with colormap doesnt work because i dont have a color list. Ive seen answers where the user manually created color mapping of categories to color. I have 40 over categories and cant do it manually.

有什么办法可以将 'ad' 列的不同值设置为自动分配颜色吗?

Is there any way to just set distinct value of 'ad' column to be automatically assigned a color?

寻找这样的东西:

推荐答案

您可以为 ad 列中存在的每个组获取不同的颜色,如下所示:

You could get distinct colours for each group present in the ad column as shown:

df.set_index(['date'],inplace=True) 

# Empty list to append later
grouped_list = []
label_list = []

# Iterating through each group key grouped by ad
for label, key in df.groupby(['ad'])['clicked']:
    grouped_list.append(key)
    label_list.append(label)

# Concatenating the grouped list column-wise and filling Nans with 0's 
df_grouped_bar = pd.concat(grouped_list, axis=1).fillna(0)

# Renaming columns created to take on new names
df_grouped_bar.columns = label_list

# Bar plot with a chosen colormap
ax = df_grouped_bar.plot(kind='bar', stacked=True, figsize=(6,6), 
                         width=0.2, ylim=(0,5000), cmap=plt.cm.rainbow)
# Figure Aesthetics
ax.set_xticklabels(df_grouped_bar.index.format())
plt.ylabel('clicked')
plt.tight_layout()
plt.show()

这篇关于 pandas 图自动为类别分配颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆