# python使用matplotlib绘制柱状图教程

Matplotlib的概念这里就不多介绍了，关于 绘图库Matplotlib的安装方法： 点击这里

1. 基本的柱状图

```
import matplotlib.pyplot as plt

data = [5, 20, 15, 25, 10]

plt.bar(range(len(data)), data)
plt.show()
```

plt.bar函数签名为：

```
bar(left, height, width=0.8, bottom=None, **kwargs)
```

• ``` (left - width / 2, bottom) ``` 为左下角位置
• ``` (left + width / 2, bottom + height) ``` 为右上角位置

```
import matplotlib.pyplot as plt

data = [5, 20, 15, 25, 10]

plt.bar([0.3, 1.7, 4, 6, 7], data, width=0.6, bottom=[10, 0, 5, 0, 5])
plt.show()
```

2. 设置柱体样式

（1）颜色

```
import matplotlib.pyplot as plt

data = [5, 20, 15, 25, 10]

plt.bar(range(len(data)), data, fc='g')
plt.show()
```

```
import matplotlib.pyplot as plt

data = [5, 20, 15, 25, 10]

plt.bar(range(len(data)), data, color='rgb') # or `color=['r', 'g', 'b']`
plt.show()
```

（2）描边

• edgecolor 或 ec
• linestyle 或 ls
• linewidth 或 lw

```
import matplotlib.pyplot as plt

data = [5, 20, 15, 25, 10]

plt.bar(range(len(data)), data, ec='r', ls='--', lw=2)
plt.show()
```

（3）填充

hatch关键字可用来设置填充样式，可取值为：/, \, |, -, +, x, o, O, ., *。例如：

```
import matplotlib.pyplot as plt

data = [5, 20, 15, 25, 10]

plt.bar(range(len(data)), data, ec='k', lw=1, hatch='o')
plt.show()
```

3. 设置tick label

```
import matplotlib.pyplot as plt

data = [5, 20, 15, 25, 10]
labels = ['Tom', 'Dick', 'Harry', 'Slim', 'Jim']

plt.bar(range(len(data)), data, tick_label=labels)
plt.show()
```

4. 堆叠柱状图

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

size = 5
x = np.arange(size)
a = np.random.random(size)
b = np.random.random(size)

plt.bar(x, a, label='a')
plt.bar(x, b, bottom=a, label='b')
plt.legend()
plt.show()
```

5. 并列柱状图

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

size = 5
x = np.arange(size)
a = np.random.random(size)
b = np.random.random(size)
c = np.random.random(size)

total_width, n = 0.8, 3
width = total_width / n
x = x - (total_width - width) / 2

plt.bar(x, a, width=width, label='a')
plt.bar(x + width, b, width=width, label='b')
plt.bar(x + 2 * width, c, width=width, label='c')
plt.legend()
plt.show()
```

6. 条形图

```
import matplotlib.pyplot as plt

data = [5, 20, 15, 25, 10]

plt.barh(range(len(data)), data)
plt.show()
```

plt.barh方法的签名为：

```
barh(bottom, width, height=0.8, left=None, **kwargs)
```

7. 正负条形图

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

a = np.array([5, 20, 15, 25, 10])
b = np.array([10, 15, 20, 15, 5])

plt.barh(range(len(a)), a)
plt.barh(range(len(b)), -b)
plt.show()
```

QQ号联系： 360901061

【本文对您有帮助就好】