如何在Jupyter Notebook中并排显示Plotly图表与Pandas DataFrame
在Jupyter Notebook中并排显示Plotly图表与Pandas DataFrame
问题描述
我需要在Jupyter Notebook里把Plotly图表和Pandas DataFrame并排展示,现在默认是上下排列的,可复现代码如下:
import pandas as pd import plotly.express as px df = px.data.iris() fig = px.scatter(df, x="sepal_width", y="sepal_length") fig.show() # 统计DataFrame df[["sepal_length", "species"]].groupby("species").agg(['mean', 'count', 'median', 'min', 'max'])
解决方案
方法1:用HTML Flex布局实现
把图表和DataFrame都转成HTML,再用CSS的flex容器让它们并排,简单直接:
import pandas as pd import plotly.express as px from IPython.display import display, HTML df = px.data.iris() fig = px.scatter(df, x="sepal_width", y="sepal_length") # 生成图表和DataFrame的HTML字符串 fig_html = fig.to_html(full_html=False) df_stats = df[["sepal_length", "species"]].groupby("species").agg(['mean', 'count', 'median', 'min', 'max']) df_html = df_stats.to_html() # 用flex布局拼接成组合HTML combined_html = f""" <div style="display: flex; gap: 20px; margin: 10px 0;"> <div style="flex: 1;">{fig_html}</div> <div style="flex: 1;">{df_html}</div> </div> """ # 渲染显示 display(HTML(combined_html))
方法2:用ipywidgets的HBox组件
利用IPython的输出组件和HBox容器来组合,适合需要后续交互的场景:
import pandas as pd import plotly.express as px import ipywidgets as widgets from IPython.display import display df = px.data.iris() fig = px.scatter(df, x="sepal_width", y="sepal_length") # 创建图表输出组件 fig_output = widgets.Output() with fig_output: fig.show() # 创建DataFrame输出组件 df_stats = df[["sepal_length", "species"]].groupby("species").agg(['mean', 'count', 'median', 'min', 'max']) df_output = widgets.Output() with df_output: display(df_stats) # 并排展示两个组件 display(widgets.HBox([fig_output, df_output]))
方法3:Plotly子图+表格组件(统一画布)
如果想把DataFrame作为表格嵌入到Plotly的画布中,可以用这种方法:
import pandas as pd import plotly.express as px import plotly.graph_objects as go from plotly.subplots import make_subplots df = px.data.iris() fig_scatter = px.scatter(df, x="sepal_width", y="sepal_length") df_stats = df[["sepal_length", "species"]].groupby("species").agg(['mean', 'count', 'median', 'min', 'max']) # 创建1行2列的子图 fig_combined = make_subplots( rows=1, cols=2, specs=[[{"type": "scatter"}, {"type": "table"}]], column_widths=[0.6, 0.4] ) # 添加散点图到第一个子图 for trace in fig_scatter.data: fig_combined.add_trace(trace, row=1, col=1) # 添加表格到第二个子图 fig_combined.add_trace( go.Table( header=dict( values=[f"{col[0]}<br>{col[1]}" for col in df_stats.columns], fill_color='#f0f8ff', align='left' ), cells=dict( values=[df_stats[col].values for col in df_stats.columns], fill_color='#f8f8ff', align='left' ) ), row=1, col=2 ) # 调整布局 fig_combined.update_layout(height=450, width=1000, title_text="散点图与统计数据") fig_combined.show()
内容的提问来源于stack exchange,提问作者Quinten
相关产品推荐
相关产品推荐

