Renata Mesquita
Renata Mesquita

Reputation: 125

Bar plot and coloured categorical variable

I have a dataframe with 3 variables:

data= [["2019/oct",10,"Approved"],["2019/oct",20,"Approved"],["2019/oct",30,"Approved"],["2019/oct",40,"Approved"],["2019/nov",20,"Under evaluation"],["2019/dec",30,"Aproved"]] 
df = pd.DataFrame(data, columns=['Period', 'Observations', 'Result'])

I want a barplot grouped by the Period column, showing all the values ​​contained in the Observations column and colored with the Result column. How can I do this?

I tried the sns.barplot, but it joined the values in Observations column in just one bar(mean of the values).

sns.barplot(x='Period',y='Observations',hue='Result',data=df,ci=None)

Plot output

Upvotes: 1

Views: 3893

Answers (2)

Tim.Lucas
Tim.Lucas

Reputation: 271

If you would like it grouped by the months, and then stacked, please use the following (note I updated your code to make sure one month had more than one status), but not sure I completely understood your question correctly:

%matplotlib inline
import pandas as pd
import matplotlib.pyplot as plt


data= [["2019/oct",10,"Approved"],["2019/oct",20,"Approved"],["2019/oct",30,"Approved"],["2019/oct",40,"Under evaluation"],["2019/nov",20,"Under evaluation"],["2019/dec",30,"Aproved"]] 
df = pd.DataFrame(data, columns=['Period', 'Observations', 'Result'])


df.groupby(['Period', 'Result'])['Observations'].sum().unstack('Result').plot(kind='bar', stacked=True)

resulting plot

Upvotes: 2

Horace
Horace

Reputation: 1054

Assuming that you want one bar for each row, you can do as follows:

import matplotlib.pyplot as plt
import matplotlib.patches as mpatches

result_cat = df["Result"].astype("category")
result_codes = result_cat.cat.codes.values
cmap = plt.cm.Dark2(range(df["Result"].unique().shape[0]))

patches = []
for code in result_cat.cat.codes.unique():
    cat = result_cat.cat.categories[code]
    patches.append(mpatches.Patch(color=cmap[code], label=cat))

df.plot.bar(x='Period', 
            y='Observations',
            color=cmap[result_codes], 
            legend=False)
plt.ylabel("Observations")
plt.legend(handles=patches)

barplot

Upvotes: 5

Related Questions