import numpy as np
import matplotlib.pyplot as plt
# 生成散点图数据
x_scatter = np.random.rand(50)
y_scatter = np.random.rand(50)
# 生成柱状图数据
x_bar = np.arange(5)
y_bar = np.random.randint(1, 10, size=5)
# 创建一个包含两个子图的图形
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 6), gridspec_kw={'hspace': 0, 'wspace': 0.3})
# 绘制散点图
scatter = ax1.scatter(x_scatter, y_scatter, color='darkred', edgecolors='black')
ax1.set_xlabel('Categories')
ax1.set_ylabel('Values')
ax1.annotate('(a)', xy=(-0.1, 1.1), xycoords='axes fraction', fontsize=12)
# 绘制柱状图
bars = ax2.bar(x_bar, y_bar, edgecolor='black')
ax2.set_xlabel('Categories')
ax2.set_ylabel('Values')
ax2.annotate('(b)', xy=(-0.1, 1.1), xycoords='axes fraction', fontsize=12)
# 去掉标题
ax1.set_title('')
ax2.set_title('')
plt.show()
代码说明:
数据生成:
使用np.random.rand生成 50 个随机数作为散点图的x和y坐标,生成范围在 0 到 1 之间。
使用np.arange生成从 0 到 4 的数组作为柱状图的x轴刻度,使用np.random.randint生成 5 个 1 到 10 之间的随机整数作为柱状图的y值。
子图创建:
plt.subplots(1, 2, figsize=(12, 6), gridspec_kw={'hspace': 0, 'wspace': 0.3})创建一个一行两列的图形,设置图形大小为(12, 6)英寸,并通过gridspec_kw参数设置子图之间的垂直间距hspace为 0,水平间距wspace为 0.3。
散点图绘制:
ax1.scatter(x_scatter, y_scatter, color='darkred', edgecolors='black')绘制散点图,点的颜色为深红色,边缘颜色为黑色。
ax1.set_xlabel('Categories')和ax1.set_ylabel('Values')设置散点图的x轴和y轴标签与柱状图一致。
ax1.annotate('(a)', xy=(-0.1, 1.1), xycoords='axes fraction', fontsize=12)在散点图的左上方图外添加标注(a)。
柱状图绘制:
ax2.bar(x_bar, y_bar, edgecolor='black')绘制柱状图,柱子边缘颜色为黑色。
ax2.set_xlabel('Categories')和ax2.set_ylabel('Values')设置柱状图的x轴和y轴标签。
ax2.annotate('(b)', xy=(-0.1, 1.1), xycoords='axes fraction', fontsize=12)在柱状图的左上方图外添加标注(b)。
去掉标题:
ax1.set_title('')和ax2.set_title('')去掉两个子图的标题。
显示图形:
plt.show()显示绘制好的图形。