前言

条形图主要以长方形的长度为变量的统计图表,常用来比较多个项目分类的数据大小。在这里我们主要分为默认条形图、横放条形图和层叠条形图。

代码

默认条形图

import numpy as np
import matplotlib.pyplot as plt

N = 5

y = [20,10,30,25,15]
index = np.arange(N)
#默认条形图
pl = plt.bar(left = index,height = y)
plt.show()

横放条形图

import numpy as np
import matplotlib.pyplot as plt

N = 5

y = [20,10,30,25,15]
index = np.arange(N)

#横放条形图
pl = plt.bar(left = 0,bottom = index,width = y,color='red',height = 0.5,orientation='horizontal')
#上一句的简写,任选一句即可
#pl = plt.barh(left = 0,bottom = index,width = y,color='red',height = 0.5)
plt.show()

层叠条形图

自下向上层叠

import numpy as np
import matplotlib.pyplot as plt

index = np.arange(4)
sales_BJ = [52,55,63,53]
sales_SH = [44,66,55,41]
bar_width = 0.3

plt.bar(index,sales_BJ,bar_width,color='b')
plt.bar(index,sales_SH,bar_width,color='r',bottom=sales_BJ)
plt.show()

自左向右层叠

import numpy as np
import matplotlib.pyplot as plt

index = np.arange(4)
sales_BJ = [52,55,63,53]
sales_SH = [44,66,55,41]
bar_width = 0.3

plt.bar(index,sales_BJ,bar_width,color='b')
plt.bar(index+bar_width,sales_SH,bar_width,color='r')
plt.show()

展示

默认条形图

条形图bar

横放条形图

条形图bar

自下向上层叠

条形图bar

自左向右层叠

条形图bar

后记

画一个条形图大概就是这样了。此例主要用来后期的学习和延伸。

相关文章: