一、竖放条形图
代码:
1 import matplotlib.pyplot as plt
2
3 # 这两行代码解决 plt 中文显示的问题
4 plt.rcParams['font.sans-serif'] = ['SimHei']
5 plt.rcParams['axes.unicode_minus'] = False
6
7 waters = ('A', 'B', 'C', 'D', 'E')
8 buy_number = [12, 28, 5, 4, 10]
9
10 plt.bar(waters, buy_number)
11 plt.title('竖放条形图')
12
13 plt.show()
效果:
二、横放条形图
代码:
1 import matplotlib.pyplot as plt
2
3 # 这两行代码解决 plt 中文显示的问题
4 plt.rcParams['font.sans-serif'] = ['SimHei']
5 plt.rcParams['axes.unicode_minus'] = False
6
7 waters = ('A', 'B', 'C', 'D', 'E')
8 buy_number = [12, 28, 5, 4, 10]
9
10 plt.barh(waters, buy_number) # 横放条形图函数 barh
11 plt.title('横放条形图')
12
13 plt.show()
效果:
三、并列条形图
代码:
1 import matplotlib.pyplot as plt
2 import numpy as np
3
4 # 这两行代码解决 plt 中文显示的问题
5 plt.rcParams['font.sans-serif'] = ['SimHei']
6 plt.rcParams['axes.unicode_minus'] = False
7
8 # 输入统计数据
9 waters = ('A', 'B', 'C', 'D', 'E')
10 buy_number_male = [6, 7, 6, 1, 2]
11 buy_number_female = [9, 4, 4, 5, 6]
12
13 bar_width = 0.3 # 条形宽度
14 index_T = np.arange(len(waters)) # T条形图的横坐标
15 index_F = index_T + bar_width # F条形图的横坐标
16
17 # 使用两次 bar 函数画出两组条形图
18 plt.bar(index_T, height=buy_number_male, width=bar_width, color='b', label='T')
19 plt.bar(index_F, height=buy_number_female, width=bar_width, color='g', label='F')
20
21 plt.legend() # 显示图例
22 plt.xticks(index_T + bar_width / 2, waters) # index_T + bar_width/2 为横坐标轴刻度的位置
23 plt.ylabel('G') # 纵坐标轴标题
24 plt.title('并列条形图') # 图形标题
25
26 plt.show()
效果:
四、条形统计图
代码:
1 import matplotlib.pyplot as plt
2 import numpy as np
3 import pandas as pd
4
5 plt.rcParams['font.sans-serif'] = ['SimHei'] # 正常显示中文
6 plt.rcParams['axes.unicode_minus'] = False # 正常显示负号
7
8 ages = range(11)
9 count = [3, 6, 7, 11, 13, 18, 15, 11, 7, 5, 4]
10 plt.bar(ages, count, label='graph 1')
11 # params
12 # x: 条形图x轴
13 # y:条形图的高度
14 # width:条形图的宽度 默认是0.8
15 # bottom:条形底部的y坐标值 默认是0
16 # align:center / edge 条形图是否以x轴坐标为中心点或者是以x轴坐标为边缘
17 plt.legend()
18 plt.xlabel('ages')
19 plt.ylabel('count')
20 plt.title(u'条形统计图')
21
22 for i in range(11):
23 plt.text(i, count[i] + 0.1, "%s" % count[i], va='center')
24
25 plt.show()
效果: