我想对我的数据框进行条形图绘制,以便分类列('ad')定义条形图的颜色。 这是我的数据:
"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个广告组。
我的代码:
columns=['date','converted','clicked','ad']
df2=pd.DataFrame(df,columns=columns)
df2.set_index(df2.date,inplace=True)
这里我只用1列('点击')来对'日''进行绘图
plt.figure()
df2.loc[:,['clicked','ad']].plot(kind='bar')
plt.show()
#df2.loc[:,['clicked','ad']].plot(kind='bar',colormap='ad')
colormap
的代码行不起作用,因为我没有颜色列表。
我见过用户手动创建颜色到颜色的颜色映射的答案。我有40个以上的类别,不能手动完成。
有没有办法只设置'ad'列的不同值以自动分配颜色?
答案 0 :(得分:0)
您可以为ad
列中显示的每个组获取不同的颜色,如下所示:
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()