本記事では、下図のような棒グラフをpandasのデータフレームにて、列名を指定して描く雛形コードを載せました。df.plot.bar()を使います。グラフの値を記入するには、ax.patchesを用います。

上図の元データは、下図のような表データです。これをpandasのDataFrame書式で列名を指定します。この例では、列名「species」がX軸ラベル、列名「petal_length」,「sepal_width」,「sepal_length」が凡例です。

■本プログラム
冒頭の左図のような普通の棒グラフを描きたい場合には、 flag_stacked にFalseを指定します。一方、右図のような積み上げ棒グラフは、 flag_stacked にTrueを指定します。
import pandas as pd
import matplotlib.pyplot as plt
plt.rcParams['font.size'] = 18
df = pd.read_csv('iris-dataset.csv')
df
DF = df.iloc[[0, 50, 100], :]
DF
y_min = 0
y_max = 20
flag_stacked = True
ax = DF.plot.bar(
rot = 20,
x = 'species',
y = {'sepal_length',
'sepal_width',
'petal_length'
},
cmap = 'cool',
stacked = flag_stacked,
figsize = (6, 5),
)
ax.set(ylabel = r'width, length [cm]',
title = 'iris dataset',
)
ax.legend(bbox_to_anchor = (1, 1))
ax.grid(axis = 'y', linestyle = 'dotted', color = 'gray')
y_offset = (y_max - y_min) * (-0.05)
for bar in ax.patches:
ax.text(
bar.get_x() + bar.get_width() * 0.5,
bar.get_height() + bar.get_y() + y_offset,
round(bar.get_height(), 1),
ha = 'center',
color = 'k',
fontweight = 'bold',
fontsize = 14,
)
以上
<広告>
リンク
リンク