Skip to content

Latest commit

 

History

History
88 lines (79 loc) · 2.2 KB

grouped-stacked-bar.md

File metadata and controls

88 lines (79 loc) · 2.2 KB
jupyter
jupytext kernelspec language_info plotly
notebook_metadata_filter text_representation
all
extension format_name format_version jupytext_version
.md
markdown
1.3
1.14.7
display_name language name
Python 3
python
python3
codemirror_mode file_extension mimetype name nbconvert_exporter pygments_lexer version
name version
ipython
3
.py
text/x-python
python
python
ipython3
3.7.7
description display_as language layout name order page_type permalink thumbnail
How to make a grouped and stacked bar chart in Python with Plotly.
statistical
python
base
Grouped Stacked Bar Charts
17
u-guide
python/grouped-stacked-bar/
thumbnail/grouped-stacked-bar.jpg

This page details the use of a figure factory. For more examples with bar charts, see this page.

Simple Grouped Stacked Bar Chart

import plotly.figure_factory as ff
import plotly.express as px

df = px.data.tips().groupby(["day", "sex", "smoker"])[["total_bill", "tip"]].sum().reset_index()

fig = ff.create_grouped_stacked_bar(
    df,
    x="smoker",
    stack_group="day",
    color="sex",
    y="tip",
)
fig.update_layout(legend_title=None)
fig.show()

Advanced Grouped Stacked Bar Chart

import plotly.figure_factory as ff
import plotly.express as px

df = px.data.tips().groupby(["day", "sex", "smoker"])[["total_bill", "tip"]].sum().reset_index()

fig = ff.create_grouped_stacked_bar(
    df,
    x="smoker",
    stack_group="day",
    color="sex",
    y="tip",
    # Manage the gap between groups
    stack_group_gap=0.2,
    # Manage the gap between bars within groups
    bar_gap=0.05,
    # Manage the category orders
    category_orders={
      "day": ["Thur", "Fri", "Sat", "Sun"],
    },
    # The grouped stacked bar chart respects the template colors
    # Each group will be displayed with nuances of the colorway
    # You can also specify the list of colors with `color_discrete_sequence`
    template="ggplot2",
    # Unified hover label
    hover_unified=True,
)
fig.update_layout(legend_title=None)
fig.show()