Matplotlibで棒グラフを作成

概要

bar_ex1

Fig1. 棒グラフ[1]

import numpy as np
import matplotlib.pyplot as plt

labels = ["2020", "2021", "2022", "2023", "2024", "2025"]
dummy_data = {
    'JP': np.array([20, 10, 15, 21, 12, 9]),
    'US': np.array([12, 21, 18, 13, 20, 7]),
    'FR': np.array([34, 14, 32, 20, 27, 18])
}

colors = [
    [(0.8, 0.8, 0.8), (0, 0, 0)],
    [(100/256, 170/256, 220/256), (0, 0, 0)],
    [(0, 15/256, 120/256), (1, 1, 1)]
]

plt.rcParams["font.family"] = "Arial"
plt.rcParams["font.size"] = 11
n = len(dummy_data)
x_years = np.arange(len(labels))
bottom = np.zeros(len(labels))

fig, ax = plt.subplots(figsize=(8.0, 4.0))
for i, (country, count) in enumerate(dummy_data.items()):
    br = ax.bar(
        x_years, count, 
        label=country, 
        tick_label=labels, 
        color=colors[i][0],
        width=0.6,
        bottom=bottom
    )
    ax.bar_label(br, labels=count, label_type="center", color=colors[i][1])
    bottom += count
ax.bar_label(br, label_type="edge")
ax.legend(edgecolor=(1,1,1))
ax.tick_params(bottom=False, left=False, right=False, top=False)
ax.tick_params(labelbottom=True, labelleft=False, labelright=False, labeltop=False)
ax.spines["right"].set_visible(False)
ax.spines["top"].set_visible(False)
ax.spines["left"].set_visible(False)