Skip to content

Instantly share code, notes, and snippets.

@tuelwer
Forked from 99991/plot_bars.py
Created December 18, 2020 07:30
Show Gist options
  • Save tuelwer/486a92347de604b25b31a605b0155eab to your computer and use it in GitHub Desktop.
Save tuelwer/486a92347de604b25b31a605b0155eab to your computer and use it in GitHub Desktop.
Plot bar chart with multiple groups of bars with matplotlib pyplot
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
# ugly hack to embed fonts
matplotlib.rc("pdf", fonttype=42)
edgecolor = "black"
bar_scale = 0.8
plt.figure(figsize=(14, 4))
things = [
{
"label": "The best",
"values": [0.4, 0.60, 0.52, 0.44, 0.2],
"color": "#00ff00",
},
{
"label": "Slightly worse",
"values": [0.3, 0.45, 0.39, 0.33, 0.15],
"color": "#dddddd",
},
{
"label": "Bad",
"values": [0.2, 0.30, 0.26, 0.22, 0.1],
"color": "#afafaf",
},
{
"label": "Trash",
"values": [0.1, 0.15, 0.13, 0.11, 0.05],
"color": "#666666",
},
]
group_labels = ["Group #1", "Group #2", "Group #3", "Group #4", "Group #5"]
for i, data in enumerate(things):
x = 1 + np.arange(len(group_labels)) + (i - (len(things) - 1) / 2) * bar_scale / len(things)
plt.bar(
x=x,
height=data["values"],
width=bar_scale / len(things),
label=data["label"],
color=data["color"],
edgecolor=edgecolor,
linewidth=0.5,
)
plt.ticklabel_format(axis="y", style="sci", scilimits=(0, 0), useMathText=True)
plt.xticks(1 + np.arange(len(group_labels)), group_labels)
plt.xlim([0.5, len(group_labels) + 0.5])
plt.ylabel("Goodness")
plt.legend()
plt.tight_layout()
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment