Python: Plotting stacked bar chart in Facet grid

Viewed 875

I have a dataframe which looks like below given:

Direction ID    RY Value Part_of_prog
      North  1  2016    29            0
      North  2  2016    25            1
      North  3  2016    25            0
      North  4  2016    22            1
      North  4  2017    22            1
      North  4  2017    24            1
      North  4  2017    25            0
      North  4  2017    26            0
      North  5  2018    26            0
      North  5  2018    26            1
      North  5  2018    20            1
      North  5  2018    22            0
      South  6  2018    22            0
      South  6  2018    22            1
      South  6  2018    24            1
      South  6  2018    24            0
      South  7  2017    24            0
      South  7  2017    24            1
      South  7  2017    19            1
      South  7  2017    18            0
      South  7  2016    13            0
      South  7  2016    13            1
      South  7  2016    14            1
      South  7  2016    19            0
      East  1  2016    29             0
      East  2  2016    15             1
      East  3  2016    25             0
      East  4  2016    22             1
      East  4  2017    22             1
      East  4  2017    14             1
      East  4  2017    25             0
      East  4  2017    26             0
      East  5  2018    16             0
      East  5  2018    26             1
      East  5  2018    10             1
      East  5  2018    22             0

I am plotting bar plot in Facet grid using seaborn using following code:

g = sns.FacetGrid(df,col='Direction')
g = g.map_dataframe(sns.barplot,"RY","Value",hue='Part_of_prog',ci=None,palette = sns.color_palette("bright"))
for ax in g.axes.ravel():
    ax.legend()
plt.show()

Which produces the following figure: enter image description here Now I want to change the bar plot to stacked bar. I want to use the facet grid to generate similar kind of layout. I used the following code to generate the figure but got an error:

  g = sns.FacetGrid(df,col='Direction')
    g = g.map_dataframe(df[['Value','RY']].plot.bar(stacked=True),hue='Part_of_prog',palette = sns.color_palette("bright"))
    for ax in g.axes.ravel():
        ax.legend()
    plt.show()

Could anyone guide me how to generate the stacked bar plot in facegrid?

1 Answers

As someone mentioned in a now-deleted comment/answer, seaborn is an opinionated data visualisation library, meaning it makes it easy to create certain (mainly statistical) types of graphs, rather than a general purpose, "build your own" tool. Stacked bars are out of scope, according to its author.

So instead, I would suggest that you create the type of graph you're after using Bokeh. The data will need to be structured in a slightly different way (stacking variable has to be pivoted into columns) and there is slightly more code to write, but that's the price of greater flexibility.

First, the data manipulation:

df["Part_of_prog"] = df["Part_of_prog"].astype(str)
df["RY"] = df["RY"].astype(str)

wide_df = (df
.pivot_table(index=["Direction", "RY"], columns="Part_of_prog", values="Value", aggfunc=sum)
.reset_index()
.rename_axis(None, axis="columns")
)

Now the visualisation part:

from bokeh.io import output_notebook, output_file, show
from bokeh.plotting import figure
from bokeh.models import ColumnDataSource, CDSView, BooleanFilter, Range1d
from bokeh.layouts import row

output_notebook() # for Jupyter Notebooks

# shared ranges for the 3 plots
x_range = df["RY"].unique()
y_range = Range1d(0, 110)

colors = ["#c9d9d3", "#718dbf"]

# shared source for all plots to allow linked brushing/panning if you need it
source = ColumnDataSource(wide_df)

# filtered views for each of the facets
east_view = CDSView(source=source, filters=[BooleanFilter(wide_df["Direction"] == "East")])
north_view = CDSView(source=source, filters=[BooleanFilter(wide_df["Direction"] == "North")])
south_view = CDSView(source=source, filters=[BooleanFilter(wide_df["Direction"] == "South")])

# plots are broadly similar, but we'll use a facet object to modify things like titles
def generate_facet_plot(facet):
    
    p = figure(x_range=x_range, y_range=y_range, plot_height=250, plot_width=200,
               title=facet["title"], toolbar_location=None, tools="")

    p.vbar_stack(stackers=["0","1"], x="RY", color=colors, width=0.9,
                 source=source, view=facet["view"])
    
    p.yaxis.visible = facet["y_axis_visible"]
    p.xgrid.visible = False
    p.y_range.start = 0

    return p

# our configuration object for facets
facets = {
    "east": {
        "title": "East",
        "view" : east_view,
        "y_axis_visible": True
    },
    "north": {
        "title": "North",
        "view" : north_view,
        "y_axis_visible": False
    },
    "south": {
        "title": "South",
        "view" : south_view,
        "y_axis_visible": False
    },
}

plots = []

for facet in facets.keys():
    plots.append(generate_facet_plot(facets[facet]))
  
# row layout; other options are available
p = row(plots)
show(p)

Result:

enter image description here

There is a lot more on styling (with examples) in Bokeh documentation.

Related