多个数据框列绘制在同一栏中,没有重叠

时间:2019-03-21 19:03:50

标签: python matplotlib bar-chart

我有一个熊猫数据框:

import pandas as pd

data1 = {'Date':['03-19-2019'],
    'Total':[35],
    'Solved':[19],
    'Arrived':[23],
    } 

 df1 = pd.DataFrame(data1)

我想绘制这样的条形图:

enter image description here

使用

df1.plot(kind='barh',x='Date',y='Total', ax=ax0, color='#C0C0C0', 
width=0.5)
df1.plot(kind='barh',x='Date',y='Arrived', ax=ax0, color='#C0FFFF', 
width=0.5)
df1.plot(kind='barh',x='Date',y='Solved', ax=ax0, color='#C0C0FF', 
width=0.5)

但是,为了避免重叠,我必须考虑到每一列的值都较大(总和大于已到达大于已解决)来绘制每一列。

如何避免这样做并轻松实现此过程的自动化?

2 个答案:

答案 0 :(得分:1)

在Pandas中必须有一种简单直接的方法,但是我只是想出了这种快速的解决方法。想法如下:

  • 省略第一列Date,然后对其余的列进行排序。
  • 使用排序后的索引以升序绘制列
  • 要使颜色一致,可以使用字典,以使升序/降序不影响您的颜色。

fig, ax0 = plt.subplots()

ids = np.argsort(df1.values[0][1:])[::-1]
colors = {'Total': '#C0C0C0', 'Arrived': '#C0FFFF', 'Solved':'#C0C0FF'}

for col in np.array(df1.columns[1:].tolist())[ids]:
    df1.plot(kind='barh',x='Date',y=col, ax=ax0, color=colors[col], width=0.1)

enter image description here

答案 1 :(得分:0)

可以通过stacked=True选项在熊猫中生成堆叠的条形图。要使用此功能,您需要首先使"Date"成为索引。

import matplotlib.pyplot as plt
import pandas as pd

data1 = {'Date':['03-19-2019'],
    'Total':[35],
    'Solved':[19],
    'Arrived':[23],
    } 

df = pd.DataFrame(data1)

df.set_index("Date").plot(kind="barh", stacked=True)

plt.show()

enter image description here