如何在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
相关产品推荐
相关产品推荐

