0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Pythonで棒グラフを描写する

Posted at

内容

棒グラフの描写方法を備忘録としてまとめておきます。
最終的な棒グラフのイメージはこちら
image.png

具体的な手順は下記になります。

# ライブラリインポート
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

今回はアヤメのデータを元にグラフを描写します。

# データ読み込み
from sklearn.datasets import load_iris
iris = load_iris()
# データフレームを作成
data = pd.DataFrame(iris.data, columns=iris.feature_names)
# ターゲットデータを追加
data['target'] = iris.target

データは下記の状態になります。
image.png

ターゲットのデータは下記に対応しています。
0 : setosa
1 : versicolor
2 : virginica

それぞれの平均値をグラフ化するコードをまとめていきます。
平均を算出する方法はGroupby関数を用いて平均を得ます。

# グループ分けするコラムを指定
group = data.groupby('target')
# 平均を得るコラムを指定
group_mean = group['sepal length (cm)'].mean() #  平均

# ラベルを指定する
labels = ["setosa","versicolor","virginica"]

# 横軸の幅を指定
left = np.arange(len(labels)) 

plt.bar(left , group_mean , width = 0.5 , label = "mean" , color = "coral")
plt.xticks(left , labels)
plt.legend()
plt.show()

あんまりにも簡単なのでfor文をもちいて一括でグラフ描写します。
まずはコラム名を取得します。
今回は一番最後に"target"があるので、スライスでコラム名を取得します。

あとはFor文で変更するだけです。

# コラム名を取得
columns = data.columns[ : -1]

# for文で一括で平均を取得&描写
# ラベルを指定する
labels = ["setosa","versicolor","virginica"] 

# 横幅を指定
width = 0.2

# 横軸の幅を指定
left = np.arange(len(labels)) 

for i, column_name in enumerate(columns):
    group_mean = group[column_name].mean() #平均
    
    #グラフ描写
    plt.bar(left + i * width  , group_mean, width= width ,label = column_name)
    plt.xticks(left + (len(columns) - 1) * width / 2, labels)
plt.legend()
plt.show()

前回の投稿と同じような内容になってしまいましたが、
平均を簡単にグラフ化できるので便利かと思います。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?