In [1]:
import matplotlib.pyplot as plt
import numpy as np
In [2]:
t = np.arange(5)
data = [5, 20, 15, 25, 10]
plt.bar(t, data, fc="g")
plt.show()
plt.bar 函数签名为:
matplotlib.pyplot.bar(x, height, width=0.8, bottom=None, *, align='center', data=None, **kwargs)
https://matplotlib.org/api/_as_gen/matplotlib.pyplot.bar.html
x,height,width,bottom 这四个参数确定了柱体的位置和大小。默认情况下,left为柱体的居中位置(可以通过align参数来改变left值的含义),即:
- (x - width / 2, bottom)为左下角位置
- (x + width / 2, bottom + height)为右上角位置
设置 rgb颜色¶
In [3]:
plt.bar(range(len(data)), data, color='rgb')
plt.show()
其他参数,边框,填充,tick_label¶
- edgecolor ec
- linestyle ls
linewidth lw
hatch / , \ , | , - , + , x , o , O , . , *
In [4]:
labels = ['Tom', 'Dick', 'Harry', 'Slim', 'Jim']
plt.bar(t, data, ec='r', ls='--', lw=2, hatch='o', tick_label=labels)
plt.show()
堆叠柱状图¶
In [5]:
size = 5
t = np.arange(size)
a = np.random.random(size)
b = np.random.random(size)
plt.bar(t, a, label='a')
plt.bar(t, b, bottom=a, label='b')
plt.legend()
plt.show()
并列图¶
这个需要自己调整,没有现成的 api
In [6]:
total_width, n = 0.8, 2
width = total_width / n
t = t - (total_width - width) / 2
plt.bar(t, a, width=width, label='a')
plt.bar(t + width, b, width=width, label='b')
plt.legend()
plt.show()
横置图¶
In [7]:
plt.barh(range(len(data)), data)
plt.show()
正负条形图¶
In [8]:
a = np.array([5, 20, 15, 25, 10])
b = np.array([10, 15, 20, 15, 5])
plt.barh(np.arange(len(a)), a)
plt.barh(np.arange(len(b)), -b)
plt.show()