I created a stacked bar graph with matplotlib in Python and added a data label

Try drawing a stacked bar graph with matplotlib

motivation

When drawing a stacked bar graph in Python, I wish I could display the data label like Excel, and when I looked it up, there was no article that could display the data label, and there was no code that I could copy and paste. So, I wrote a code that I can copy and paste when I want to add a data label to the stacked bar graph.

By the way, if you only need to draw a stacked bar graph, please refer to ** Easy to draw a stacked bar graph ** at the end of this page.

import

Import the following libraries.


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

sns.set(font='IPAexGothic')

%matplotlib inline

Creating dummy data

Dummy data created monthly sales data for A, B, and C branches.


dataset = pd.DataFrame([[100, 200, 50], [300, 400, 600], [50, 300, 60]], 
                       columns=['Branch A', 'B branch', 'C branch'], 
                       index=['April', 'May', 'June'])
Branch A B branch C branch
April 100 200 50
May 300 400 600
June 50 300 60

Draw a bar graph

First, let's draw a simple bar graph. Let's draw a bar graph that totals the monthly sales of each branch. It's good to draw, but with this alone, I don't know how much sales each month. .. .. In such a case, let's use a stacked bar graph!

fig, ax = plt.subplots(figsize=(10, 8))
ax.bar(dataset.columns, dataset.sum())
plt.show()

image.png

Draw a stacked bar graph

Stacked bar charts use ʻax.bar () as you would when drawing a bar chart. Specify the y coordinate that is the base of the bar in the argument bottom` at this time. You now have a stacked bar chart! !! !! After all, I want a data label. Reference site: https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.axes.Axes.bar.html


fig, ax = plt.subplots(figsize=(10, 8))
for i in range(len(dataset)):
    ax.bar(dataset.columns, dataset.iloc[i], bottom=dataset.iloc[:i].sum())
ax.set(xlabel='Branch name', ylabel='Sales')
ax.legend(dataset.index)
plt.show()

image.png

Display data labels in stacked bar charts

The main subject is finally from here. Insert the data label by specifying the x and y coordinates with plt.text (). Then I got a good feeling!


fig, ax = plt.subplots(figsize=(10, 8))
for i in range(len(dataset)):
    ax.bar(dataset.columns, dataset.iloc[i], bottom=dataset.iloc[:i].sum())
    for j in range(len(dataset.columns)):
        plt.text(x=j, 
                 y=dataset.iloc[:i, j].sum() + (dataset.iloc[i, j] / 2), 
                 s=dataset.iloc[i, j], 
                 ha='center', 
                 va='bottom'
                )
ax.set(xlabel='Branch name', ylabel='Sales')
ax.legend(dataset.index)
plt.show()

image.png

Draw a 100% stacked bar graph

When you use a stacked bar chart, you also want to use a 100% stacked bar chart. First, process the data. The following code converts sales by branch into percentages.


plot_dataset = pd.DataFrame(index = dataset.index)
for col in dataset.columns:
    plot_dataset[col] = round(100 * dataset[col] / dataset[col].sum(), 1)
Branch A B branch C branch
April 22.2 22.2 7.0
May 66.7 444. 84.5
June 11.1 33.3 8.5

Draw a 100% stacked bar chart using the converted data. The code is the same as the previous code. (Only variables are changed.)


fig, ax = plt.subplots(figsize=(10, 8))
for i in range(len(plot_dataset)):
    ax.bar(plot_dataset.columns, 
           plot_dataset.iloc[i], 
           bottom=plot_dataset.iloc[:i].sum()
          )
    for j in range(len(plot_dataset.columns)):
        plt.text(x=j, 
                 y=plot_dataset.iloc[:i, j].sum()+(plot_dataset.iloc[i, j]/2), 
                 s=f'{plot_dataset.iloc[i, j]}%', 
                 ha='center', 
                 va='bottom'
                )
ax.set(xlabel='Branch name', ylabel='Sales')
ax.legend(plot_dataset.index)
plt.show()

image.png

Easily draw stacked bar charts

If you just want to draw a stacked bar graph, you can easily draw it with the following code.

fig, ax = plt.subplots(figsize=(10, 8))
dataset.T.plot(kind='bar', stacked=True, ax=ax)
plt.show()

image.png

Recommended Posts

I created a stacked bar graph with matplotlib in Python and added a data label
I created a class in Python and tried duck typing
Graph time series data in Python using pandas and matplotlib
[Graph drawing] I tried to write a bar graph of multiple series with matplotlib and seaborn
Easily graph data in shell and Python
I created a password tool in Python.
(Matplotlib) I want to draw a graph with a size specified in pixels
Read Python csv data with Pandas ⇒ Graph with Matplotlib
I wrote a class in Python3 and Java
Use libsixel to output Sixel in Python and output a Matplotlib graph to the terminal.
Create a stacked graph corresponding to both positive and negative directions with matplotlib
[Python] How to draw a line graph with Matplotlib
I want to work with a robot in python.
I made a LINE BOT with Python and Heroku
[Python, ObsPy] I wrote a beach ball with Matplotlib + ObsPy
Sample data created with python
Graph Excel data with matplotlib (1)
Graph Excel data with matplotlib (2)
Try running python in a Django environment created with pipenv
Study math with Python: Draw a sympy (scipy) graph with matplotlib
I made a simple typing game with tkinter in Python
Let's create a PRML diagram with Python, Numpy and matplotlib.
I made a puzzle game (like) with Tkinter in Python
I wrote python3.4 in .envrc with direnv and allowed it, but I got a syntax error
I also tried to imitate the function monad and State monad with a generator in Python
A python graphing manual with Matplotlib.
I want to solve APG4b with Python (only 4.01 and 4.04 in Chapter 4)
I added Maki Horikita and Kanna Hashimoto and divided by 2 with python
I made a fortune with Python.
Get data from MySQL on a VPS with Python 3 and SQLAlchemy
I want to create a graph with wavy lines omitted in the middle with matplotlib (I want to manipulate the impression)
Draw a watercolor illusion with edge detection in Python3 and openCV3
I tried to make a periodical process with Selenium and Python
Hashing data in R and Python
I played with PyQt5 and Python3
Heatmap with Dendrogram in Python + matplotlib
Let's make a graph with python! !!
I made a daemon with Python
Write a stacked histogram with matplotlib
Let's use Python to represent the frequency of binary data contained in a data frame in a single bar graph.
Calculate the shortest route of a graph with Dijkstra's algorithm and Python
How to send a visualization image of data created in Python to Typetalk
I tried Python! ] Titanic data _vol.1 (bar graph, scatter plot, correlation coefficient)
I set the environment variable with Docker and displayed it in Python
How to draw a bar graph that summarizes multiple series with matplotlib
I have 0 years of programming experience and challenge data processing with python
Plot CSV of time series data with unixtime value in Python (matplotlib)
Join data with main key (required) and subkey (optional) in Python pandas
Create a Python3 environment with pyenv on Mac and display a NetworkX graph
Make a decision tree from 0 with Python and understand it (4. Data structure)
Get additional data in LDAP with python
Data pipeline construction with Python and Luigi
Spiral book in Python! Python with a spiral book! (Chapter 14 ~)
[Python] Set the graph range with matplotlib
I made a payroll program in Python!
Add a Python data source with Redash
Try working with binary data in Python
I made a character counter with Python
I drew a heatmap with seaborn [Python]
A memo with Python2.7 and Python3 on CentOS
Created a darts trip with python (news)