Python matplotlib数据可视化 subplot绘制多个子图

2021-01-23 14:05:06 浏览数 (1)

数据可视化的时候,有时需要将多个子图放在同一个画板上进行比较。通过使用GridSpec类配合subplot,可以很容易对子区域进行划定和选择,在同一个画板上绘制多个子图。

1. 对子绘图区域的划定和选择

GridSpec是matplotlib中一个特殊的用来进行子绘图区域设计和选定的一个类

代码语言:txt复制
import matplotlib.gridspec as gridspec
gs = gridspec.GridSpec(2, 2)   # 设计一个网格 2行2列
# 选定子绘图区域
ax1 = plt.subplot(gs[0, 0])
ax2 = plt.subplot(gs[0, 1])
ax3 = plt.subplot(gs[1, 0])
ax4 = plt.subplot(gs[1, 1])

通过使用GridSpec类配合subplot,可以很容易对子区域进行划定和选择。

2. 绘制多个子图

测试数据如下:

代码如下:

代码语言:txt复制
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib as mpl
import matplotlib.gridspec as gridspec
import collections
import numpy as np

# 读取数据
df = pd.read_csv('soccer.csv', encoding='gbk')

# 子图1数据
skill_count = df['Skill_Moves'].value_counts()
skill = [f'等级{m}' for m in skill_count.index]    # 列表推导式构造不同技术等级
counts = skill_count.values.tolist()               # 技术等级对应人数统计的列表

# 子图2数据
age_group = ["17-26", "27-36", "37-47"]
count_1 = df[(df['Age'] >= 17) & (df['Age'] <= 26)]
count_2 = df[(df['Age'] >= 27) & (df['Age'] <= 36)]
count_3 = df[(df['Age'] >= 37) & (df['Age'] <= 47)]
age_counts = [len(count_1), len(count_2), len(count_3)]

# 子图3数据
# &符号 并且    |符号 或   不同条件之间 ()括起来
data1 = df[(17 <= df['Age']) & (df['Age'] <= 26)]
age1 = list(data1['Skill_Moves'])
data2 = df[(27 <= df['Age']) & (df['Age'] <= 36)]
age2 = list(data2['Skill_Moves'])
data3 = df[(37 <= df['Age']) & (df['Age'] <= 47)]
age3 = list(data3['Skill_Moves'])

# 分别统计三个年龄段 不同等级人数
count_1 = collections.Counter(age1).most_common()
count_2 = collections.Counter(age2).most_common()
count_3 = collections.Counter(age3).most_common()
count_3.append((5, 0))    # 37-47年龄段等级5人数为零  手动填上
age_counts3 = count_1   count_2   count_3

datas = [[] for i in range(5)]
for i in age_counts3:
	datas[i[0]-1].append(i[1])

grades = np.array(datas)

# 子图4数据
skill_moves = list(df['Skill_Moves'])
skill_count = collections.Counter(skill_moves).most_common()
skill = ['等级{}'.format(m[0]) for m in skill_count]
counts = [n[1] for n in skill_count]

# 绘制多个子图
mpl.rcParams['font.family'] = 'SimHei'
gs = gridspec.GridSpec(2, 2)
plt.figure(figsize=(12, 20), dpi=100)

ax1 = plt.subplot(gs[0, 0])
ax2 = plt.subplot(gs[0, 1])
ax3 = plt.subplot(gs[1, 0])
ax4 = plt.subplot(gs[1, 1])

ax1.barh(skill[::-1], counts[::-1], height=0.5, color='#FF00FF')
ax1.set_xlabel('人数')
ax1.set_title('不同技术等级人数统计')

ax2.bar(age_group, age_counts, width=0.35, color='red')
ax2.set_title('不同年龄段人数统计')
ax2.set_xlabel('年龄段')
ax2.set_ylabel('人数')

ax3.bar(age_group, grades[0], label='等级一', color='red', width=0.35)
ax3.bar(age_group, grades[1], bottom=grades[0], label="等级二", color="#9400D3", width=0.35)
ax3.bar(age_group, grades[2], bottom=grades[0]   grades[1], label="等级三", color="#0000FF", width=0.35)  # 转化为数组  直接相加
ax3.bar(age_group, grades[3], bottom=grades[0]   grades[1]   grades[2], label="等级四", color="#FFFF00", width=0.35)
ax3.bar(age_group, grades[4], bottom=grades[0]   grades[1]   grades[2]   grades[3], label="等级五", color="#006400", width=0.35)
ax3.set_title('不同年龄段等级人数统计')
ax3.set_xlabel('年龄段')
ax3.set_ylabel('人数')

x_ = [1, 0, 0, 0, 0]	   # 用于显示空心
color = ["red", "blue", "yellow", "green", "purple"]
# 正圆
ax4.set_aspect(aspect='equal')
ax4.pie(x=counts, colors=color, pctdistance=0.9,
		startangle=45, autopct='%.1f%%',
		)

ax4.pie(x_, radius=0.65, colors="w")   # 小的空白圆填充
ax4.set_title('不同技术等级的运动员人数占比图')
# 调整图例位置
plt.legend(skill, bbox_to_anchor=(0.9, 0.92))
plt.show()

运行效果如下:

作者:叶庭云 微信公众号:修炼Python CSDN:https://yetingyun.blog.csdn.net/ 本文仅用于交流学习,未经作者允许,禁止转载,更勿做其他用途,违者必究。 觉得文章对你有帮助、让你有所收获的话,期待你的点赞呀,不足之处,也可以在评论区多多指正。

0 人点赞