Pyplot(1)  棒グラフ

# 棒グラフまとめ
## 縦棒グラフ
### 基本形

必要なライブラリをインポートします。

```Python:
import numpy as np
import matplotlib.pyplot as plt
```
データを準備します。データはlistでもarrayでも大丈夫でした。

```Python:
means = [20, 34, 30, 35, 27]
```
各棒の横幅を設定します。

```Python:
x = np.arange(len(labels))
width = 0.35
```

グラフを表示します。

```Python:
plt.bar(x, men_means, width)
plt.show()
```
まとめると以下のようになります。

```Python:
import numpy as np
import matplotlib.pyplot as plt

means = [20, 34, 30, 35, 27]

x = np.arange(len(labels))
width = 0.35

plt.bar(x, men_means, width)
plt.show()
```

![image_01.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/476387/428019a5-e873-4106-b348-c052f78e7b52.png)

### タイトル・ラベル追加
`plt.xlabel`でx軸方向のラベル、`plt.ylabel`でy軸方向のラベル、`plt.tile`でタイトルをそれぞれ設定できます。

```Python:
plt.xlabel('Group')
plt.ylabel('Scores')
plt.title('Scores by group')
```
![image_02.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/476387/86db30d7-12d8-7cbf-aa04-f4087a183e96.png)

### 棒ごとのラベル追加

```Python:
import numpy as np
import matplotlib.pyplot as plt

labels = ['label1', 'label2', 'label3', 'label4', 'label5']
means = [20, 34, 30, 35, 27]

x = np.arange(len(labels))
width = 0.35

fig, ax = plt.subplots()

rect = ax.bar(x, men_means, width)
ax.set_xticks(x)
ax.set_xticklabels(labels)

plt.show()
```

`ax.set_xticks(x)`を省略すると、棒ごとのラベルの位置がずれるので注意。

![bar_02.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/476387/efbb44b6-dcb1-b3b6-797b-63b85c681ffb.png)

### 棒の上に値を表示

```Python:
import numpy as np
import matplotlib.pyplot as plt

labels = ['label1', 'label2', 'label3', 'label4', 'label5']
means = [20, 34, 30, 35, 27]

x = np.arange(len(labels))
width = 0.35

fig, ax = plt.subplots()

rect = ax.bar(x, men_means, width)
ax.set_xticks(x)
ax.set_xticklabels(labels)

def autolabel(rects):
    for rect in rects:
        height = rect.get_height()
        ax.annotate('{}'.format(height),
                   xy=(rect.get_x() + rect.get_width() / 2, height),
                   xytext=(0, 3),
                   textcoords="offset points",
                   ha='center', va='bottom')
autolabel(rect)      
plt.show()
```
![bar_01.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/476387/7b33d831-b7bc-7eba-0a79-3d4837097013.png)

### regend

```Python:
import numpy as np
import matplotlib.pyplot as plt

labels = ['label1', 'label2', 'label3', 'label4', 'label5']
means = [20, 34, 30, 35, 27]

x = np.arange(len(labels))
width = 0.35

fig, ax = plt.subplots()

rect = ax.bar(x, men_means, width, label='Men')
ax.set_xticks(x)
ax.set_xticklabels(labels)
ax.legend()

def autolabel(rects):
    for rect in rects:
        height = rect.get_height()
        ax.annotate('{}'.format(height),
                   xy=(rect.get_x() + rect.get_width() / 2, height),
                   xytext=(0, 3),
                   textcoords="offset points",
                   ha='center', va='bottom')
autolabel(rect)      

plt.show()
```
![bar_03.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/476387/69a510dc-f8ed-e5b4-ca49-238112a7fe63.png)

左上に表示させたい場合は以下のようにします。

```Python:
ax.legend(loc='upper left')
```
![bar_04.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/476387/bf4d13e3-26b8-c612-2c44-532473d80e3b.png)

### 横並び

1種の場合とほとんど同様なのですが、表示させる位置をずらしてあげることで2つ並んでいるように見せることができます。

```Python:
import matplotlib
import matplotlib.pyplot as plt
import numpy as np

labels = ['G1', 'G2', 'G3', 'G4', 'G5']
men_means = [20, 34, 30, 35, 27]
women_means = [25, 32, 34, 20, 25]

x = np.arange(len(labels))
width = 0.35

fig, ax = plt.subplots()
rects1 = ax.bar(x - width/2, men_means, width, label='Men')
rects2 = ax.bar(x + width/2, women_means, width, label='Women')

ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.set_xlabel('test')
ax.set_xticks(x)
ax.set_xticklabels(labels)
ax.legend()

def autolabel(rects):
    for rect in rects:
        height = rect.get_height()
        ax.annotate('{}'.format(height),
                   xy=(rect.get_x() + rect.get_width() / 2, height),
                   xytext=(0, 3),
                   textcoords="offset points",
                   ha='center', va='bottom')
        
autolabel(rects1)
autolabel(rects2)

fig.tight_layout()

plt.show()
```
![image_04.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/476387/93306dca-5198-ef5b-f277-2f584c8ea069.png)


## 積み上げ縦棒グラフ

```Python:
import numpy as np
import matplotlib.pyplot as plt

labels = ['G1', 'G2', 'G3', 'G4', 'G5']
men_means = [20, 34, 30, 35, 27]
women_means = [25, 32, 34, 20, 25]
menStd = [2, 3, 4, 1, 2]
womenStd = [3, 5, 2, 3, 3]

x = np.arange(len(labels))
width = 0.35

p1 = plt.bar(x, men_means, width, yerr=menStd)
p2 = plt.bar(x, women_means, width, bottom=men_means, yerr=womenStd)
plt.ylabel('Scores')
plt.title('Scores by group and gender')
plt.xticks(x, labels)
plt.yticks(np.arange(0, 81, 10))
plt.legend((p1[0], p2[0]), ('Men', 'Women'))

plt.show()
```
![image_03.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/476387/7fc8708c-30f6-ce7d-aa6c-e6fa7454925e.png)

## 横棒グラフ

`bar`ではなく`barh`を使えば、横方向の棒グラフを描画できます。
縦方向の場合と比較して、ラベルなどを設定する軸が変わることに注意が必要です。

```Python:
import matplotlib.pyplot as plt
import numpy as np

np.random.seed(19680801)

plt.rcdefaults()
fig, ax = plt.subplots()

people = ('Tom', 'Dick', 'Harry', 'Slim', 'Jim')
y_pos = np.arange(len(people))
performance = 3 + 10 * np.random.rand(len(people))
error = np.random.rand(len(people))

ax.barh(y_pos, performance, xerr=error, align='center')
ax.set_yticks(y_pos)
ax.set_yticklabels(people)
ax.invert_yaxis()
ax.set_xlabel('Performance')
ax.set_title('How fast do you want to go today?')
```
![image_05.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/476387/70b29de5-c99b-9ad8-cd65-8f4c385f5182.png)