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

如何在Jupyter Notebook同一单元格中绘制多幅散点图?

解决方案:在同一单元格并排绘制多个散点图

没问题!要在同一个单元格里并排展示三个DataFrame的price与索引的散点图,用Matplotlib的子图(subplots)功能就能轻松实现。我给你准备了完整的可运行示例,你直接替换成自己的DataFrame就行:

完整示例代码(Matplotlib版本)

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

# 模拟你的三个DataFrame(替换成你自己的数据即可)
np.random.seed(42)  # 保证结果可复现
df1 = pd.DataFrame({'price': np.random.randn(100).cumsum()}, index=pd.date_range('2023-01-01', periods=100))
df2 = pd.DataFrame({'price': np.random.randn(100).cumsum()}, index=pd.date_range('2023-01-01', periods=100))
df3 = pd.DataFrame({'price': np.random.randn(100).cumsum()}, index=pd.date_range('2023-01-01', periods=100))

# 创建1行3列的子图布局,figsize控制整体画布大小
fig, (ax1, ax2, ax3) = plt.subplots(nrows=1, ncols=3, figsize=(18, 6))

# 绘制第一个散点图
ax1.scatter(df1.index, df1['price'], color='blue', alpha=0.6)
ax1.set_title('Price vs Index (DataFrame 1)', fontsize=12)
ax1.set_xlabel('Index', fontsize=10)
ax1.set_ylabel('Price', fontsize=10)
ax1.tick_params(axis='x', rotation=45)  # 旋转x轴标签,避免日期/长索引重叠

# 绘制第二个散点图
ax2.scatter(df2.index, df2['price'], color='green', alpha=0.6)
ax2.set_title('Price vs Index (DataFrame 2)', fontsize=12)
ax2.set_xlabel('Index', fontsize=10)
ax2.tick_params(axis='x', rotation=45)

# 绘制第三个散点图
ax3.scatter(df3.index, df3['price'], color='red', alpha=0.6)
ax3.set_title('Price vs Index (DataFrame 3)', fontsize=12)
ax3.set_xlabel('Index', fontsize=10)
ax3.tick_params(axis='x', rotation=45)

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

关键说明

  • nrows=1, ncols=3:指定子图布局为1行3列,刚好放下三个图
  • figsize=(18,6):控制整体画布的宽度和高度,你可以根据需求调整数值
  • ax1/ax2/ax3:分别对应三个子图的坐标轴对象,所有绘图操作都针对指定轴进行
  • tight_layout():自动优化子图间距,避免元素重叠,非常实用

可选:Seaborn版本(更美观的样式)

如果你偏好Seaborn的可视化风格,代码逻辑基本一致,只需要替换绘图函数:

import seaborn as sns

fig, (ax1, ax2, ax3) = plt.subplots(nrows=1, ncols=3, figsize=(18, 6))

# 用Seaborn绘制散点图,指定ax参数绑定到对应子图
sns.scatterplot(x=df1.index, y=df1['price'], ax=ax1, color='blue', alpha=0.6)
sns.scatterplot(x=df2.index, y=df2['price'], ax=ax2, color='green', alpha=0.6)
sns.scatterplot(x=df3.index, y=df3['price'], ax=ax3, color='red', alpha=0.6)

# 后续设置标题、标签、调整布局的代码和之前一致
ax1.set_title('Price vs Index (DataFrame 1)', fontsize=12)
ax2.set_title('Price vs Index (DataFrame 2)', fontsize=12)
ax3.set_title('Price vs Index (DataFrame 3)', fontsize=12)

plt.tight_layout()
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:21:55