You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在同一单元格中绘制两组独立的Matplotlib散点图?

嘿,这个问题我太懂了!要把两个独立的散点图放到同一个单元格(不管是Jupyter Notebook的单元格还是脚本里的同一块画布)展示,核心就是用Matplotlib的子图布局功能,把两个图塞进同一个画布的不同区域就行。我给你整理了具体的实现思路和代码示例:

核心思路

不要每次绘制完一个图就单独调用plt.show(),而是先创建一个包含多个子图的画布,然后分别在每个子图上完成绘图,最后统一展示整个画布。

代码示例(1行2列布局)

假设你原来的代码是分别单独绘制kmeans_3和kmeans_4的散点图,现在改成这样:

import matplotlib.pyplot as plt

# 创建1行2列的子图布局,figsize可以按需调整整体大小
fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, figsize=(12, 5))

# 第一个子图:绘制kmeans_3的聚类结果
ax1.scatter(X_std[:, 0], X_std[:, 1], c=kmeans_3.labels_, cmap='viridis')
ax1.set_title('K-means (3 Clusters)')
ax1.set_xlabel('Standardized Feature 1')
ax1.set_ylabel('Standardized Feature 2')

# 第二个子图:绘制kmeans_4的聚类结果
ax2.scatter(X_std[:, 0], X_std[:, 1], c=kmeans_4.labels_, cmap='viridis')
ax2.set_title('K-means (4 Clusters)')
ax2.set_xlabel('Standardized Feature 1')
ax2.set_ylabel('Standardized Feature 2')

# 自动调整子图间距,避免标签、标题重叠
plt.tight_layout()

# 统一展示所有子图(Jupyter Notebook里可以省略,但脚本中必须加)
plt.show()

扩展:多组特征对比的布局

如果要展示多组标准化特征的对比(比如特征1vs2、特征3vs4),可以扩展成2行2列的布局,分别对应两种聚类结果的不同特征组合:

import matplotlib.pyplot as plt

# 创建2行2列的子图布局
fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(14, 10))

# 第一行:kmeans_3的不同特征组合
axes[0, 0].scatter(X_std[:, 0], X_std[:, 1], c=kmeans_3.labels_, cmap='viridis')
axes[0, 0].set_title('3 Clusters: Feature 1 vs Feature 2')
axes[0, 1].scatter(X_std[:, 2], X_std[:, 3], c=kmeans_3.labels_, cmap='viridis')
axes[0, 1].set_title('3 Clusters: Feature 3 vs Feature 4')

# 第二行:kmeans_4的不同特征组合
axes[1, 0].scatter(X_std[:, 0], X_std[:, 1], c=kmeans_4.labels_, cmap='viridis')
axes[1, 0].set_title('4 Clusters: Feature 1 vs Feature 2')
axes[1, 1].scatter(X_std[:, 2], X_std[:, 3], c=kmeans_4.labels_, cmap='viridis')
axes[1, 1].set_title('4 Clusters: Feature 3 vs Feature 4')

# 调整布局避免重叠
plt.tight_layout()
plt.show()

关键注意点

  • 不要在每个子图绘制后单独调用plt.show(),否则会强制分开显示图像;
  • 用ax.set_title()、ax.set_xlabel()这类子图对象的方法来设置标签,而不是全局的plt.title(),这样每个子图的配置是独立的;
  • cmap参数可以按需更换,比如'rainbow'、'plasma'等,让聚类颜色更区分。

内容的提问来源于stack exchange,提问作者slmsshk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 09:27:44