Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

Horizontal stacked percentage bar chart - matplotlib documentation

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.get_cmap('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
        ax.barh(labels, widths, left=starts, height=0.5,
                label=colname, color=color)
        xcenters = starts + widths / 2

        r, g, b, _ = color
        text_color = 'white' if r * g * b < 0.5 else 'darkgrey'
        for y, (x, c) in enumerate(zip(xcenters, widths)):
            ax.text(x, y, str(int(c)), ha='center', va='center',
                    color=text_color)
    ax.legend(ncol=len(category_names), bbox_to_anchor=(0, 1),
              loc='lower left', fontsize='small')

    return fig, ax


survey(results, category_names)
plt.show()
Comment

PREVIOUS NEXT
Code Example
Python :: patoolib extract password-protected archives 
Python :: connection to python debugger failed: socket closed 
Python :: The most appropriate graph for your data 
Python :: python typing namedtuple 
Python :: mystring = "hello" myfloat=float 10 myint=20 
Python :: create date by column values pandas 
Python :: delta lake with spark 
Python :: change label in dataframe per condition 
Python :: Basic 13 Algorithm 
Python :: Drop multiple consecutive columns 
Python :: python matrices access column 
Python :: filetype: env "DB_PASSWORD" 
Python :: empty show non python 
Python :: custom_settings in scrpay 
Python :: place a number randomly in a list python 
Python :: how to resize image with pillow in django 
Python :: provide a script that prints the sum of every even numbers in the range [0; 100]. 
Python :: evaluate value of polynomial in python code 
Python :: python calculate variance by hand 
Python :: why am i not able to import wtf flask 
Python :: how to write a correct python code 
Python :: sorting-a-dictionary-by-value-then-by-key 
Python :: concatenate dataframes using one column 
Python :: Return a new RDD containing the distinct elements in this RDD. 
Python :: radice n esima python 
Python :: pandas drop a list of rows 
Python :: come traferire file python 
Python :: permutations in python 
Python :: remove grid from 3d plots 
Python :: how to change array of arrays to simpe array 
ADD CONTENT
Topic
Content
Source link
Name
6+5 =