Horizontal stacked bar chart python

To plot stacked bar chart in Matplotlib, we can use barh[] methods

Steps

  • Set the figure size and adjust the padding between and around the subplots.
  • Create a list of years, issues_addressed and issues_pending, in accordance with years.
  • Plot horizontal bars with years and issues_addressed data.
  • To make stacked horizontal bars, use barh[] method with years, issues_pending and issues_addressed data
  • Place the legend on the plot.
  • To display the figure, use show[] method.

Example

from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

year = [2014, 2015, 2016, 2017, 2018, 2019]
issues_addressed = [10, 14, 0, 10, 15, 15]
issues_pending = [5, 10, 50, 2, 0, 10]

b1 = plt.barh[year, issues_addressed, color="red"]

b2 = plt.barh[year, issues_pending, left=issues_addressed, color="yellow"]

plt.legend[[b1, b2], ["Completed", "Pending"], title="Issues", loc="upper right"]

plt.show[]

Output

Updated on 15-Jun-2021 12:25:28

  • Related Questions & Answers
  • Python Pandas - Plot a Stacked Horizontal Bar Chart
  • How to create horizontal stacked bar chart using ggvis in R?
  • How to display stacked bar chart using matplotlib in Python?
  • How to Create a Diverging Stacked Bar Chart in Matplotlib?
  • Python Pandas - Create a Horizontal Bar Chart
  • How to create a stacked bar chart for my DataFrame using Seaborn in Matplotlib?
  • How to create a stacked bar chart using JavaFX?
  • How to create stacked bar chart using ggvis in R?
  • Displaying horizontal bar graphs using Matplotlib
  • How to create a 100% stacked Area Chart with Matplotlib?
  • Stacked-to-horizontal Bootstrap Grid
  • Create stacked bar chart with percentages on Y-axis using ggplot2 in R.
  • Adding value labels on a matplotlib bar chart
  • How to create broken horizontal bar graphs in matplotlib?
  • Bootstrap Grid Stacked to horizontal grid

I'm trying to create a horizontal stacked bar chart using matplotlib but I can't see how to make the bars actually stack rather than all start on the y-axis.

Here's my testing code.

fig = plt.figure[]
ax = fig.add_subplot[1,1,1]
plot_chart[df, fig, ax]
ind = arange[df.shape[0]]      
ax.barh[ind, df['EndUse_91_1.0'], color='#FFFF00']
ax.barh[ind, df['EndUse_91_nan'], color='#FFFF00']
ax.barh[ind, df['EndUse_80_1.0'], color='#0070C0']
ax.barh[ind, df['EndUse_80_nan'], color='#0070C0']
plt.show[]

Edited to use left kwarg after seeing tcaswell's comment.

fig = plt.figure[]
ax = fig.add_subplot[1,1,1]
plot_chart[df, fig, ax]
ind = arange[df.shape[0]]      
ax.barh[ind, df['EndUse_91_1.0'], color='#FFFF00']
lefts = df['EndUse_91_1.0']
ax.barh[ind, df['EndUse_91_nan'], color='#FFFF00', left=lefts]
lefts = lefts + df['EndUse_91_1.0']
ax.barh[ind, df['EndUse_80_1.0'], color='#0070C0', left=lefts]
lefts = lefts + df['EndUse_91_1.0']
ax.barh[ind, df['EndUse_80_nan'], color='#0070C0', left=lefts]
plt.show[]

This seems to be the right approach, but it fails if there is no data for a particular bar as it's trying to add nan to a value which then returns nan.

Note

Click here to download the full example code

Stacked bar charts can be used to visualize discrete distributions.

This example visualizes the result of a survey in which people could rate their agreement to questions on a five-element scale.

The horizontal stacking is achieved by calling barh[] for each category and passing the starting point as the cumulative sum of the already drawn bars via the parameter left.

import numpy as np
import matplotlib.pyplot as plt


category_names = ['Strongly disagree', 'Disagree',
                  'Neither agree nor disagree', 'Agree', 'Strongly agree']
results = {
    'Question 1': [10, 15, 17, 32, 26],
    'Question 2': [26, 22, 29, 10, 13],
    'Question 3': [35, 37, 7, 2, 19],
    'Question 4': [32, 11, 9, 15, 33],
    'Question 5': [21, 29, 5, 5, 40],
    'Question 6': [8, 19, 5, 30, 38]
}


def survey[results, category_names]:
    """
    Parameters
    ----------
    results : dict
        A mapping from question labels to a list of answers per category.
        It is assumed all lists contain the same number of entries and that
        it matches the length of *category_names*.
    category_names : list of str
        The category labels.
    """
    labels = list[results.keys[]]
    data = np.array[list[results.values[]]]
    data_cum = data.cumsum[axis=1]
    category_colors = plt.colormaps['RdYlGn'][
        np.linspace[0.15, 0.85, data.shape[1]]]

    fig, ax = plt.subplots[figsize=[9.2, 5]]
    ax.invert_yaxis[]
    ax.xaxis.set_visible[False]
    ax.set_xlim[0, np.sum[data, axis=1].max[]]

    for i, [colname, color] in enumerate[zip[category_names, category_colors]]:
        widths = data[:, i]
        starts = data_cum[:, i] - widths
        rects = ax.barh[labels, widths, left=starts, height=0.5,
                        label=colname, color=color]

        r, g, b, _ = color
        text_color = 'white' if r * g * b 

Chủ Đề