python图分组条形图 [英] python plot grouped bar graph
问题描述
我有3列数据,如下所示
I have a 3 column data like below
clm1 clm2 clm3
|["shared","connect"] 13297 |aaaa|
|["stopped","failed] 25002 |aaaa|
|["success","obtained"] 11189 |aaaa|
|["shared","connect"] 16770 |bbbb|
|["stopped","failed] 81777 |bbbb|
|["success","obtained"] 9555 |bbbb|
我想要在 python 中使用下面的条形图,我可以写简单的图形,但无法编写可以对 clm3 和绘图进行分组的逻辑
I want below kind of bar graph in python, I am able to write simple graphs, but not able get a logic to write which can group the clm3 and plot
推荐答案
这里的主要问题是 matplotlib 认为你所有的分类数据A"代表同一个类别,所以它把它们绘制在A"的同一个地方.我们必须发明一个额外的类别来区分所有那些"A"值.例如,我们可以使用 cumcount()
将所有值A"从 0 到 n 编号.一个例子是:
The main problem here is that matplotlib thinks that all your categorical data "A" represent the same category, so it plots them in the same place for "A". We have to invent an additional category to distinguish all those "A" values. We can do this for instance with cumcount()
which numbers all values "A" from 0 to n. An example would be:
from matplotlib import pyplot as plt
import pandas as pd
#create toy dataframe
#this part you should have included in your question
#as a Minimal, Complete, and Verifiable example
np.random.seed(1234)
df = pd.DataFrame({"cat": ["A", "B", "C", "C", "B", "C", "A"], "val": np.random.randint(1, 100, 7)})
#add column for multiple cat values and rearrange dataframe
df["cols"] = df.groupby("cat").cumcount()
df1 = df.pivot(index = "cat", columns = "cols", values = "val")
print(df1)
#plot this table
df1.plot.bar(color = "blue", edgecolor = "white")
plt.legend().set_visible(False)
plt.xticks(rotation = 0)
plt.show()
示例数据框:
cols 0 1 2
cat
A 48.0 16.0 NaN
B 84.0 77.0 NaN
C 39.0 54.0 25.0
示例图:
我只是注意到,在您的情况下,它更容易,因为虽然您的问题中从未提到过这一点,但您可能想要类别clm1".因此,您可以简化程序:
I just noticed that in your case it is even easier, because, although this is never mentioned in your question, you probably want as categories "clm1". Therefore, you can simplify the procedure:
from matplotlib import pyplot as plt
import pandas as pd
#create toy dataframe
np.random.seed(1234)
df = pd.DataFrame({"clm1": ["X", "Y", "Z", "X", "Y", "Z"], "clm2": np.random.randint(1, 100, 6), "clm3": ["A", "A", "A", "B", "B", "B"]})
#rearrange dataframe and plot
df.pivot(index = "clm3", columns = "clm1", values = "clm2").plot.bar(edgecolor = "white")
plt.xticks(rotation = 0)
plt.show()
示例输出:
这篇关于python图分组条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!