简体   繁体   中英

Adding more bars to plot

I have an excel file looking like this:

| Dept.               | Q1 Budget | Q1 Actual | Q2 Budget | Q2 Actual | Q3 Budget | Q3 Actual | Q4 Budget | Q4 Actual |
|---------------------|-----------|-----------|-----------|-----------|-----------|-----------|-----------|-----------|
| Distribution        | 470,000   | 476,300   | 476,300   | 482,000   | 400,000   | 470,000   | 610,000   | 408,000   |
| Facilities          | 676,300   | 674,000   | 800,500   | 847,000   | 763,000   | 714,000   | 763,000   | 770,000   |
| Human Resources     | 363,000   | 432,000   | 463,000   | 442,000   | 463,000   | 440,000   | 443,000   | 467,000   |
| Information Systems | 763,000   | 726,300   | 863,000   | 870,000   | 876,300   | 776,000   | 700,000   | 740,000   |

I want to plot the quarters next to each other with the department as the label, with actual and budget as grouped bars, and the plot i would want to end up with would look something like this:

在此处输入图像描述

This is my code thus far:

df = pd.read_excel(file)

cols = df['Dept.']
df = df.T
df.columns = cols
df = df.tail(-1)

x = np.arange(4)
width = 0.30

plt.bar(x-0.15, df.loc['Q1 Actual'], width, color='cornflowerblue')
plt.bar(x+0.15, df.loc['Q1 Budget'], width, color='cornflowerblue', alpha=0.2)
plt.xticks(x, cols, rotation=45)

And this gives me the plot i want for the 1st quarter, looking like this:

在此处输入图像描述

How would i go about to extend my plot, to include every quarter?

Your data is in wide format, you would find it easier to do this if you melt your data into long format. Additionally the seaborn plotting library makes using a categorical variable for coloring the bars very simple.

import seaborn as sns
import pandas as pd

# Make plot bigger
sns.set(rc={'figure.figsize':(16,9)})

df = pd.DataFrame({'Dept.':['Q1 Actual','Q1 Budget', 'Q2 Actual', 'Q2 Budget'],
                  'Distribution':[476300, 470000, 482000, 476300],
                  'Facilities':[674000, 676300, 847000, 800500],
                  'Human Resources': [432000, 363000, 442000, 463000],
                  'Information Systems': [726300, 763000, 870000, 863000]})

df = df.melt(id_vars='Dept.', var_name='Function', value_name='Expenditure')

p = df.loc[df['Dept.'].str.startswith('Q1')]
sns.barplot(data=p, x='Function',y='Expenditure', hue='Dept.');

在此处输入图像描述

Alternatively you could plot them all at once with:

df['Quarter'] = df['Dept.'].str.split(' ').str[0]
g = sns.FacetGrid(df, col='Quarter', height=10)
g.map_dataframe(sns.barplot, x='Function', y='Expenditure', hue='Dept.')

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM