3.数据可视化进阶
3.1 常用视图
3.1.1 折线图
import numpy as np import matplotlib.pyplot as plt y = np.random.randint(0, 10, size = 15) # 一图多线 plt.figure(figsize = (9, 6)) # 只给了y,不给x,则x有默认值:0、1、2、3、... plt.plot(y, marker = '*', color = 'r') plt.plot(y.cumsum(), marker = 'o') # 多图布局 fig,axs = plt.subplots(2, 1) # 设置宽高 fig.set_figwidth(9) fig.set_figheight(6) axs[0].plot(y, marker = '*', color = 'red') axs[1].plot(y.cumsum(), marker = 'o')
3.1.2 柱状图
3.1.2.1 堆叠柱状图
import numpy as np import matplotlib.pyplot as plt labels = ['G1', 'G2', 'G3', 'G4', 'G5','G6'] # 级别 # 生成数据 men_means = np.random.randint(20, 35, size = 6) women_means = np.random.randint(20, 35, size = 6) men_std = np.random.randint(1, 7, size = 6) women_std = np.random.randint(1, 7, size = 6) width = 0.35 # 柱状图中柱的宽度 plt.bar(labels, # 横坐标 men_means, # 柱高 width, # 线宽 yerr = men_std, # 误差条(标准差) label = 'Men') # 标签 plt.bar(labels, women_means, width, yerr = women_std, bottom = men_means, # 把女生画成男生的上面 # 没有上一行代码柱状图会发生重叠覆盖,读者可以自行尝试 label = 'Women') plt.ylabel('Scores') plt.title('Scores by group and gender') plt.legend()
3.1.2.2 分组带标签柱状图
import matplotlib import matplotlib.pyplot as plt import numpy as np # 创造数据 labels = ['G1', 'G2', 'G3', 'G4', 'G5','G6'] # 级别 men_means = np.random.randint(20, 35,size = 6) women_means = np.random.randint(20, 35,size = 6) x = np.arange(len(men_means)) plt.figure(figsize = (9, 6)) # 把男生的柱状图整体左移 width / 2 rects1 = plt.bar(x - width / 2, men_means, width) # 把女生的柱状图整体右移 width / 2 rects2 = plt.bar(x + width / 2, women_means, width) # 设置标签标题,图例 plt.ylabel('Scores') plt.title('Scores by group and gender') plt.xticks(x, labels) plt.legend(['Men','Women']) # 放置文本 text def set_label(rects): for rect in rects: height = rect.get_height() # 获取高度 plt.text(x = rect.get_x() + rect.get_width() / 2, # 水平坐标 y = height + 0.5, # 竖直坐标 s = height, # 文本 ha = 'center') # 水平居中 set_label(rects1) set_label(rects2) # 设置紧凑布局 plt.tight_layout()