本記事では、表題のことを成す雛形コードを記載しました。点は平均値で、上下に伸びてるエラーバーがここでは±3σを表します。

グラフ化する例題データは、下図のようなcsvファイルです。A列「month」をx軸にして、B列「data」に対してmonthのカテゴリ別に平均値と3σを計算してY軸にします。

■本プログラム
import pandas as pd
import math
import matplotlib.pyplot as plt
plt.rcParams['font.size'] = 18
df = pd.read_csv('test_data.csv')
df
x_colmun = 'month'
x_list = df.groupby(x_colmun).count().reset_index()[x_colmun].tolist()
print(x_list)
print(type(x_list))
mean_list = []
shiguma_list = []
y_column = 'data'
for x in x_list:
df_buf = df[df[x_colmun] == x]
mean_buf = df_buf[y_column].mean()
mean_list.append(mean_buf)
std_buf = df_buf[y_column].std(axis=0) * 3
shiguma_list.append(std_buf)
print(shiguma_list)
print(mean_list)
fig = plt.figure(dpi=100)
color = 'b'
plt.scatter(x_list, mean_list, c=color, label='test_A')
plt.errorbar(x_list, mean_list, yerr = shiguma_list, marker = 'o', capthick = 1, capsize = 10, lw = 2, c=color)
plt.ylabel('Y [N]')
plt.title('Y vs X')
x_list2 = map(lambda x: str(x) + 'mo.', x_list)
plt.xticks(x_list, x_list2)
ax = plt.gca()
ax.set_facecolor('lightyellow')
y_min, y_max = ax.get_ylim()
ax.set_ylim(0, math.ceil(y_max))
y_spec = 3
plt.hlines(y_spec, x_list[0], x_list[-1], 'r', linestyles='dashed')
plt.text(x_list[0], y_spec + 0.1, r'Spec 3[N]', size=18, color='r')
ax.legend(bbox_to_anchor=(1, 0.95))
plt.grid()
plt.show()
以上
<広告>
リンク
リンク