7
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Matplotlibの棒グラフの横軸の順番が勝手に入れ替わるときの対処法

Last updated at Posted at 2019-04-30

Matplotlibで, x軸にカテゴリ変数, y軸に数値をとるような棒グラフを描きたいとき, グラフが思った通りの順番に並ばないことがあります。

改善前 〜棒グラフが思った通りに並ばない〜

コード

import numpy as np
import matplotlib.pyplot as plt

# 棒グラフをyの値が大きい順に並べたい
data = np.array(['much', 1.11], ['more', 2.22], ['most', 3.33])

# dataをyの降順にソート
data_sorted = data[np.argsort(data[:,1])[::-1]]

# x, yの配列を取得
x = data_sorted[:, 0]  #['most', 'more', 'much']
y = data_sorted[:, 1].astype(np.float64)  #[3.33, 2.22, 1.11]

# 棒グラフを描画する
fig = plt.figure()
ax1 = fig.add_subplot(1, 2, 1)
ax1.bar(x, y)
plt.show()

結果

配列x, yをyの降順となるようにソートした状態で棒グラフを描画しました。
しかし, 棒グラフはそのように並んでいません。

53AAC8FD-6837-451A-9154-93F869DF7C8A.png

なぜでしょうか?

グラフの描画時にデータが自動的にxの昇順となるようにソートされてしまうため, グラフが more -> most -> much のようにxに関する辞書順で並んでしまうようです。

改善後

改善する方法の1つとして「x軸の値そのもの」と「x軸のラベルに振る値」を分離するというアイディアがあります。

コード

'''
    先ほどの続き
    x = ['most', 'more', 'much']
    y = [3.33, 2.22, 1.11]
'''

# [0, 1.11], [1, 2.22], [2. 3.33] がプロットされた棒グラフのx軸に ['most', 'more', 'much'] の順でラベルを振る
x_temp = range(len(x))
ax2 = fig.add_subplot(1, 2, 2)
ax2.bar(x_temp, y, tick_label=x, color='green')

# 描画
fig.subplots_adjust(wspace=0.4)
plt.show()

結果

今度は狙いどおり, 左側からyの降順となるよう棒グラフを並べることができました。
079DECE9-3D9B-41A6-B906-5B0C5C15380B.png

7
3
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
7
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?