Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a FacetGrid stacked barplot using Seaborn?

I am trying to plot a facet_grid with stacked bar charts inside.

I would like to use Seaborn. Its barplot function does not include a stacked argument.

I tried to use FacetGrid.map with a custom callable function.

import pandas as pd
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt

def custom_stacked_barplot(col_day, col_time, col_total_bill, **kwargs):
    dict_df={}
    dict_df['day']=col_day
    dict_df['time']=col_time
    dict_df['total_bill']=col_total_bill
    df_data_graph=pd.DataFrame(dict_df)
    df = pd.crosstab(index=df_data_graph['time'], columns=tips['day'], values=tips['total_bill'], aggfunc=sum)
    df.plot.bar(stacked=True)

tips=sns.load_dataset("tips")
g = sns.FacetGrid(tips, col='size',  row='smoker')
g = g.map(custom_stacked_barplot, "day", 'time', 'total_bill')

However I get an empty canvas and stacked bar charts separately.

Empty canvas:

enter image description here

Graph1 apart:

enter image description here

Graph2:.

enter image description here

How can I fix this issue? Thanks for the help!

like image 571
rod41 Avatar asked Jun 05 '20 16:06

rod41


People also ask

How do I make a stacked bar chart in Seaborn?

A stacked Bar plot is a kind of bar graph in which each bar is visually divided into sub bars to represent multiple column data at once. To plot the Stacked Bar plot we need to specify stacked=True in the plot method. We can also pass the list of colors as we needed to color each sub bar in a bar.

How do you use FacetGrid in Seaborn?

Plotting Small Multiples of Data SubsetsA FacetGrid can be drawn with up to three dimensions − row, col, and hue. The first two have obvious correspondence with the resulting array of axes; think of the hue variable as a third dimension along a depth axis, where different levels are plotted with different colors.

How to create Stacked bar plot in Seaborn in Python?

In this article, we will discuss how to create stacked bar plot in Seaborn in Python. A stacked Bar plot is a kind of bar graph in which each bar is visually divided into sub bars to represent multiple column data at once. To plot the Stacked Bar plot we need to specify stacked=True in the plot method.

How to create a stacked bar chart for my Dataframe using Seaborn?

How to create a stacked bar chart for my DataFrame using Seaborn in Matplotlib? To create a stacked bar chart, we can use Seaborn's barplot () method, i.e., show point estimates and confidence intervals with bars. Create df using Pandas Data Frame.

What is Seaborn facetgrid?

Seaborn.FacetGrid uses many arguments as input, main of which are described below in form of table: Tidy (“long-form”) dataframe where each column is a variable and each row is an observation. Variables that define subsets of the data, which will be drawn on separate facets in the grid.

How to plot a stacked bar plot in Excel?

A stacked Bar plot is a kind of bar graph in which each bar is visually divided into sub bars to represent multiple column data at once. To plot the Stacked Bar plot we need to specify stacked=True in the plot method. We can also pass the list of colors as we needed to color each sub bar in a bar.


Video Answer


2 Answers

The simplest code to achive that result is this:

import seaborn as sns
import matplotlib.pyplot as plt
sns.set()

tips=sns.load_dataset("tips")
g = sns.FacetGrid(tips, col = 'size',  row = 'smoker', hue = 'day')
g = (g.map(sns.barplot, 'time', 'total_bill', ci = None).add_legend())

plt.show()

which gives this result:

enter image description here

like image 63
Zephyr Avatar answered Oct 16 '22 18:10

Zephyr


Your different mixes of APIs (pandas.DataFrame.plot) appears not to integrate with (seaborn.FacetGrid). Since stacked bar plots are not supported in seaborn plotting, consider developing your own version with matplotlib subplots by iterating across groupby levels:

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

def custom_stacked_barplot(t, sub_df, ax):
    plot_df = pd.crosstab(index=sub_df["time"], columns=sub_df['day'], 
                           values=sub_df['total_bill'], aggfunc=sum)

    p = plot_df.plot(kind="bar", stacked=True, ax = ax, 
                     title = " | ".join([str(i) for i in t]))   
    return p

tips = sns.load_dataset("tips")
g_dfs = tips.groupby(["smoker", "size"])

# INITIALIZE PLOT
# sns.set()
fig, axes = plt.subplots(nrows=2, ncols=int(len(g_dfs)/2)+1, figsize=(15,6))

# BUILD PLOTS ACROSS LEVELS
for ax, (i,g) in zip(axes.ravel(), sorted(g_dfs)):
    custom_stacked_barplot(i, g, ax)

plt.tight_layout()
plt.show()
plt.clf()
plt.close()

Plot Output 1

And use seaborn.set to adjust theme and pallette:

Plot Output 2

like image 36
Parfait Avatar answered Oct 16 '22 18:10

Parfait