通过分隔一列的多列条形图

问题描述

我这里有一个相同的数据框。

type    c1  c2  c3  c4  c5  c6
A       0   20  14  4   100 0
B       10  30  23  9   12  0
C       20  10  0   20  24  34

我要绘制条形图相同的图像。 matplotlib python

enter image description here

解决方法

我使用“类型”作为索引转换了数据格式,并以单行三列格式输出了“熊猫”图。

import matplotlib.pyplot as plt
import pandas as pd
import io

data = '''
type c1 c2 c3 c4 c5 c6
A 0 20 14 4 100 0
B 10 30 23 9 12 0
C 20 10 0 20 24 34
'''

df = pd.read_csv(io.StringIO(data),sep='\s+',index_col=0)
df = df.T
df.plot(kind='bar',subplots=True,layout=(1,3))

plt.show()

enter image description here

,

只需show()保留每个情节

import matplotlib.pyplot as plt
data = """type    c1  c2  c3  c4  c5  c6
A       0   20  14  4   100 0
B       10  30  23  9   12  0
C       20  10  0   20  24  34"""
a = [[t for t in l.split(" ") if t!=""] for l in data.split("\n")]

df = pd.DataFrame(a[1:],columns=a[0])
df = df.astype({c:"int64" for c in df.columns if "c" in c})


for i,r in df.iterrows():
    df.iloc[i,1:].T.plot.bar(title=df.loc[i,"type"])   
    plt.show()