[英]How can I change the color of a grouped bar plot in Pandas?
I have this plot that you'll agree is not very pretty.我有这个 plot,你会同意它不是很漂亮。 Other plots I made so far had some color and grouping to them out of the box.到目前为止,我制作的其他图都有一些颜色,并且开箱即用。
I tried manually setting the color, but it stays black.我尝试手动设置颜色,但它保持黑色。 What am I doing wrong?我究竟做错了什么? Ideally it'd also cluster the same tags together.理想情况下,它还会将相同的标签聚集在一起。
df.groupby(['tags_0', 'gender']).count().plot(kind='barh', legend=False, color=['r', 'g', 'b'])
You need to unstack your results: 您需要拆开结果:
df.groupby(['tags_0', 'gender']).gender.count().unstack().plot(kind='barh', legend=False, color=['r', 'g', 'b'])
I don't have your data, so just used a value of one for each tag/gender combo. 我没有您的数据,因此每个标签/性别组合只使用一个值。
You need to flatten your data. 您需要整理数据。 Using unstack() is one way. 使用unstack()是一种方法。 Alternatively, you can use pivot_table(). 另外,您可以使用pivot_table()。 Here is the code. 这是代码。
import pandas as pd
# try to simulate your data
characters = 'Tank Support Marksman Mage Figher Assassin'.split(' ')
random_weight = abs(np.random.randn(len(characters)))
random_weight = random_weight / random_weight.sum()
gender = 'male female'.split(' ')
index1 = np.random.choice(characters, size=1000, p=random_weight)
index2 = np.random.choice(gender, size=1000, p=[0.4, 0.6])
multi_index = pd.MultiIndex.from_tuples(list(zip(index1, index2)), names=['character', 'gender'])
data = pd.DataFrame(np.random.randn(1000), columns=['value'], index=multi_index)
data.reset_index(inplace=True)
# do your groupby
group_counts = data.groupby(['character', 'gender']).count().reset_index()
# do pivot table
table = pd.pivot_table(group_counts, index='gender', columns='character', values='value')
# set your own colors here
table.plot(kind='barh', color=['r', 'g', 'b', 'k', 'm', 'y'])
This is how you can make a unstacked bar chart.这就是制作非堆叠条形图的方法。
df_plot = df.groupby(["colomn", "colomn2"]).colomn2.count()
#create bar plot by group
df_plot.plot(kind='bar', color=[ 'r', 'b'])
(note: all the colomns need to be filled) (注意:所有栏目都需要填写)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.