Laura
Laura

Reputation: 1282

Multiple data frame columns plotted in the same bar without overlapping

I have a pandas dataframe:

import pandas as pd

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

 df1 = pd.DataFrame(data1)

and I want to plot a bar plot like this:

enter image description here

with

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)

However, to avoid overlapping, I have to draw each column taking into account which of them has the bigger value.(Total greater than Arrived greater than Solved)

How can I avoid to do this and automate this process easily?

Upvotes: 0

Views: 297

Answers (2)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339052

A stacked bar graph can be produced in pandas via the stacked=True option. To use this you need to make the "Date" the index first.

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

Upvotes: 0

Sheldore
Sheldore

Reputation: 39042

There must be a straightforward and simpler approach in Pandas but I just came up with this quick workaround. The idea is following:

  • Leave out the first column Date and sort the remaining columns.
  • Use the sorted indices for plotting the columns in ascending order
  • To make the colors consistent, you can make use of dictionary so that the ascending/descending order doesn't affect your colors.

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

Upvotes: 1

Related Questions