Ben Chuanlong Du's Blog

It is never too late to learn.

Tips on Matplotlib

Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!

In [2]:
import matplotlib.pyplot as plt
import numpy as np

# data from https://allisonhorst.github.io/palmerpenguins/

species = (
    "Adelie\n $\\mu=$3700.66g",
    "Chinstrap\n $\\mu=$3733.09g",
    "Gentoo\n $\\mu=5076.02g$",
)
weight_counts = {
    "Below": np.array([70, 31, 58]),
    "Above": np.array([82, 37, 66]),
}
width = 0.5

fig, ax = plt.subplots()
bottom = np.zeros(3)

for boolean, weight_count in weight_counts.items():
    p = ax.bar(species, weight_count, width, label=boolean, bottom=bottom)
    bottom += weight_count

ax.set_title("Number of penguins with above average body mass")
ax.legend(loc="upper right")

plt.show()
In [4]:
import pandas as pd

# data from https://allisonhorst.github.io/palmerpenguins/
df = pd.DataFrame(data={
    "species": [
            "Adelie\n $\\mu=$3700.66g",
            "Chinstrap\n $\\mu=$3733.09g",
            "Gentoo\n $\\mu=5076.02g$",
        ],
        "below": [70, 31, 58],
        "above": [82, 37, 66],
    })
df
Out[4]:
species below above
0 Adelie\n $\mu=$3700.66g 70 82
1 Chinstrap\n $\mu=$3733.09g 31 37
2 Gentoo\n $\mu=5076.02g$ 58 66
In [12]:
df.plot.bar(
    x="species",
    y=[
        "below",
        "above",
    ],
    label=[
        "Below",
        "Above",
    ],
    color=[
        "red",
        "green",
    ],
    rot=0,
    xlabel="Species",
    ylabel="Count",
    title="Number of penguins with above average body mass",
    figsize=(16, 10),
    stacked=True,
)
Out[12]:
<Axes: title={'center': 'Number of penguins with above average body mass'}, xlabel='Species', ylabel='Count'>
In [ ]:
 

Comments