'22/09/10更新:棒グラフの値の表示位置設定とグリッド設定について、引数を明記しました(グラフデザインの柔軟性を高めた雛形コードにするため)。
本記事では、下図のような横に並べる棒グラフの雛形コードを載せました。

上記のデータ元は、下図のようなcsvファイルです。凡例はcsvファイル別を表し、x軸ラベルは各ファイルの行方向のデータです。

■本プログラム
import glob
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['font.size'] = 18
import japanize_matplotlib
file_path_list = glob.glob('*.csv')
file_path_list
df1 = pd.read_csv(file_path_list[0])
df1
category_list = df1['Subject'].tolist()
category_list
x1 = np.arange(len(category_list)).tolist()
x2 = list(map(lambda x: x + 0.3, x1))
x3 = list(map(lambda x: x + 0.6, x1))
x_position_list = [x1, x2, x3]
print(x_position_list)
y_name = 'score'
my_color_list = ['r', 'y', 'b']
fig, ax = plt.subplots(figsize = (13, 4))
for i, (_file, _x_pos) in enumerate(zip(file_path_list, x_position_list)):
_df = pd.read_csv(_file)
bar = ax.bar(_x_pos,
_df[y_name],
width = 0.3,
color = my_color_list[i],
alpha = 0.5,
edgecolor = my_color_list[i],
label = _file,
)
ax.bar_label(bar,
color = 'k',
label_type = 'edge',
padding = -25)
plt.legend(bbox_to_anchor=(1,1))
plt.xticks(x2, category_list)
plt.ylabel(y_name)
plt.title('成績')
plt.grid(axis = 'y', linestyle = 'dashed', color = 'gray')
plt.show()
plt.savefig(y_name + '.jpg')
以上
<広告>
リンク
リンク