0
点赞
收藏
分享

微信扫一扫

数据驱动成功:小程序积分商城的数据分析

孟佳 2023-09-17 阅读 51

 目录

1 基本子图绘制示例

2 子图网格布局

3 调整子图的尺寸

4 多行多列的子图布局

5 子图之间的共享轴

6 绘制多个子图类型

7 实战:

绘制一个大图,里面包含6个不同类别的子图,不均匀布局。


绘制子图(subplots)是在Matplotlib中创建多个子图的常见任务。通过子图,您可以将多个图形放置在同一图表中,以便比较不同的数据或可视化多个相关的图形。一般流程如下:

1 基本子图绘制示例

首先,让我们看一个基本的子图绘制示例。使用plt.subplots()函数,您可以创建一个包含多个子图的图表,并将这些子图放置在一个网格中。以下是一个基本的示例:

import matplotlib.pyplot as plt
import numpy as np

# 创建示例数据
x = np.linspace(0, 2 * np.pi, 100)
y1 = np.sin(x)
y2 = np.cos(x)

# 创建一个包含两个子图的图表
fig, axes = plt.subplots(nrows=1, ncols=2)

# 在第一个子图中绘制正弦函数
axes[0].plot(x, y1, label='Sine Function', color='blue')
axes[0].set_title('Sine Function')

# 在第二个子图中绘制余弦函数
axes[1].plot(x, y2, label='Cosine Function', color='red')
axes[1].set_title('Cosine Function')

# 显示图例
axes[0].legend()
axes[1].legend()

# 显示图形
plt.show()

运行:

2 子图网格布局

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import numpy as np

# 创建示例数据
x = np.linspace(0, 2 * np.pi, 100)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.tan(x)

# 创建一个包含多个子图的图表,使用gridspec定义子图布局
fig = plt.figure(figsize=(10, 4))
gs = gridspec.GridSpec(1, 3)  # 1行3列的子图布局

# 第一个子图
ax1 = plt.subplot(gs[0, 0])
ax1.plot(x, y1, label='Sine Function', color='blue')
ax1.set_title('Sine Function')
ax1.legend()

# 第二个子图
ax2 = plt.subplot(gs[0, 1])
ax2.plot(x, y2, label='Cosine Function', color='red')
ax2.set_title('Cosine Function')
ax2.legend()

# 第三个子图
ax3 = plt.subplot(gs[0, 2])
ax3.plot(x, y3, label='Tangent Function', color='green')
ax3.set_title('Tangent Function')
ax3.legend()

# 调整子图之间的距离
plt.tight_layout()

# 显示图形
plt.show()

运行: 

3 调整子图的尺寸

您可以通过设置gridspec中每个子图的相对宽度来调整子图的尺寸。以下示例将第一个子图的宽度设置为其他两个子图的两倍:

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import numpy as np

# 创建示例数据
x = np.linspace(0, 2 * np.pi, 100)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.tan(x)

# 创建一个包含多个子图的图表,使用gridspec定义子图布局
fig = plt.figure(figsize=(12, 4))

 # 1行3列的子图布局,第一个子图宽度为其他两个的两倍
gs = gridspec.GridSpec(1, 3, width_ratios=[2, 1, 1]) 

# 第一个子图
ax1 = plt.subplot(gs[0, 0])
ax1.plot(x, y1, label='Sine Function', color='blue')
ax1.set_title('Sine Function')
ax1.legend()

# 第二个子图
ax2 = plt.subplot(gs[0, 1])
ax2.plot(x, y2, label='Cosine Function', color='red')
ax2.set_title('Cosine Function')
ax2.legend()

# 第三个子图
ax3 = plt.subplot(gs[0, 2])
ax3.plot(x, y3, label='Tangent Function', color='green')
ax3.set_title('Tangent Function')
ax3.legend()

# 调整子图之间的距离
plt.tight_layout()

# 显示图形
plt.show()

4 多行多列的子图布局

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import numpy as np

# 创建示例数据
x = np.linspace(0, 2 * np.pi, 100)
y = np.sin(x)

# 创建一个包含多行多列子图的图表,使用gridspec定义子图布局
fig = plt.figure(figsize=(10, 6))
gs = gridspec.GridSpec(3, 2)  # 3行2列的子图布局

# 绘制多行多列的子图
for i in range(3):
    for j in range(2):
        ax = plt.subplot(gs[i, j])
        ax.plot(x, y, label='Sine Function', color='blue')
        ax.set_title(f'Subplot ({i+1}, {j+1})')
        ax.legend()

# 调整子图之间的距离
plt.tight_layout()

# 显示图形
plt.show()

运行: 

5 子图之间的共享轴

import matplotlib.pyplot as plt
import numpy as np

# 创建示例数据
x = np.linspace(0, 2 * np.pi, 100)
y1 = np.sin(x)
y2 = np.cos(x)

# 创建一个包含多个子图的图表
fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True, figsize=(8, 6))

# 第一个子图,共享X轴
ax1.plot(x, y1, label='Sine Function', color='blue')
ax1.set_title('Shared X-Axis')
ax1.legend()

# 第二个子图,共享X轴
ax2.plot(x, y2, label='Cosine Function', color='red')
ax2.legend()

# 调整子图之间的距离
plt.tight_layout()

# 显示图形
plt.show()

运行: 

共享Y轴示例:

import matplotlib.pyplot as plt
import numpy as np

# 创建示例数据
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)

# 创建两个子图,共享Y轴
fig, (ax1, ax2) = plt.subplots(1, 2, sharey=True, figsize=(10, 4))

# 在第一个子图上绘制sin函数
ax1.plot(x, y1, label='Sine Function', color='blue', linestyle='--')
ax1.set_title('Subplot 1: Sine Function')
ax1.set_xlabel('X-axis')
ax1.set_ylabel('Y-axis')
ax1.legend()

# 在第二个子图上绘制cos函数
ax2.plot(x, y2, label='Cosine Function', color='red', linestyle='-')
ax2.set_title('Subplot 2: Cosine Function')
ax2.set_xlabel('X-axis')
ax2.legend()

# 添加整体标题
plt.suptitle('Two Subplots Sharing Y-Axis', fontsize=16, fontweight='bold')

# 显示图形
plt.show()

运行: 

6 绘制多个子图类型

import matplotlib.pyplot as plt
import numpy as np

# 创建示例数据
x = np.linspace(0, 2 * np.pi, 100)
y1 = np.sin(x)
y2 = np.cos(x)
x_scatter = np.random.rand(50) * 2 * np.pi
y_scatter = np.sin(x_scatter)

# 创建一个包含多个子图的图表
fig, axs = plt.subplots(2, 2, figsize=(10, 6))

# 第一个子图:线图
axs[0, 0].plot(x, y1, label='Sine Function', color='blue')
axs[0, 0].set_title('Line Plot')
axs[0, 0].legend()

# 第二个子图:散点图
axs[0, 1].scatter(x_scatter, y_scatter, label='Scatter Points', color='red', marker='o')
axs[0, 1].set_title('Scatter Plot')
axs[0, 1].legend()

# 第三个子图:线图
axs[1, 0].plot(x, y2, label='Cosine Function', color='green')
axs[1, 0].set_title('Line Plot')
axs[1, 0].legend()

# 第四个子图:散点图
axs[1, 1].scatter(x_scatter, y_scatter, label='Scatter Points', color='purple', marker='s')
axs[1, 1].set_title('Scatter Plot')
axs[1, 1].legend()

# 调整子图之间的距离
plt.tight_layout()

# 显示图形
plt.show()

运行: 

7 实战:

绘制一个大图,里面包含6个不同类别的子图,不均匀布局。

import matplotlib.pyplot as plt
import numpy as np

# 创建示例数据
x = np.linspace(0, 2 * np.pi, 100)
y = np.sin(x)

# 创建图形
fig = plt.figure(figsize=(12, 8))

 # 在上方添加母图标题
fig.suptitle('Customized Subplots Example', fontsize=16, fontweight='bold') 

# fig.suptitle('Customized Subplots Example', fontsize=16, fontweight='bold', y=0.05) # 在下方添加母图标题

# 调整子图的布局,增加垂直间距,避免子图之间有交叉
plt.subplots_adjust(hspace=0.5)

# 第一行,一个子图,绘制线图
ax1 = fig.add_subplot(3, 1, 1)
ax1.plot(x, y, color='blue', label='Sine Function', linewidth=2, linestyle='--', marker='o', markersize=5)
ax1.set_title('Line Plot', fontsize=14)
ax1.set_facecolor('lightgray')
ax1.set_xlabel('X-axis', fontsize=12)
ax1.set_ylabel('Y-axis', fontsize=12)
ax1.legend()

# 添加注释
ax1.annotate('Peak Point', xy=(np.pi/2, 1), xytext=(np.pi/2, 1.2),
             arrowprops=dict(facecolor='black', shrink=0.05),
             fontsize=12, bbox=dict(boxstyle='round,pad=0.3', edgecolor='black', facecolor='yellow'))

# 第二行,两个子图,一个散点图,一个柱状图
ax2 = fig.add_subplot(3, 2, 3)
ax2.scatter(x, y, color='red', label='Scatter Plot', s=20)
ax2.set_title('Scatter Plot', fontsize=14)
ax2.set_facecolor('lightyellow')
ax2.set_xlabel('X-axis', fontsize=12)
ax2.set_ylabel('Y-axis', fontsize=12)
ax2.legend()

ax3 = fig.add_subplot(3, 2, 4)
ax3.bar(x, y, color='green', label='Bar Plot', alpha=0.7)
ax3.set_title('Bar Plot', fontsize=14)
ax3.set_facecolor('lightgreen')
ax3.set_xlabel('X-axis', fontsize=12)
ax3.set_ylabel('Y-axis', fontsize=12)
ax3.legend()

# 第三行,三个子图,一个直方图,一个饼图,一个箱线图
ax4 = fig.add_subplot(3, 3, 7)
ax4.hist(y, bins=20, color='purple', label='Histogram', alpha=0.7)
ax4.set_title('Histogram', fontsize=14)
ax4.set_facecolor('lightpink')
ax4.set_xlabel('X-axis', fontsize=12)
ax4.set_ylabel('Frequency', fontsize=12)
ax4.legend()

ax5 = fig.add_subplot(3, 3, 8)
ax5.pie([len(y[y > 0]), len(y[y < 0])], labels=['Positive', 'Negative'], colors=['orange', 'lightblue'], autopct='%1.1f%%')
ax5.set_title('Pie Chart', fontsize=14)
ax5.set_facecolor('lightcoral')
ax5.legend()

ax6 = fig.add_subplot(3, 3, 9)
ax6.boxplot(y, vert=False, widths=0.3, patch_artist=True, boxprops=dict(facecolor='lightgray'))
ax6.set_title('Box Plot', fontsize=14)
ax6.set_facecolor('lightblue')
ax6.set_xlabel('X-axis', fontsize=12)
ax6.legend([])  # 添加空的图例以解决警告

# 调整子图布局
plt.tight_layout()

# 显示图形
plt.show()

运行:

举报

相关推荐

0 条评论