不幸的是plotly subplots 不直接支持plotly.express 数字,如文档here 中所述。
但是,当您使用 fig1 = px.scatter(df, x="...", y="...", color="..") 创建 plotly.express 图形时,实际上是在创建一个图形,其中 fig1.data 是 go.Scatter 跟踪的元组。您可以访问 fig1.data 中的每个跟踪并将其添加到您的 subplots 对象。
如果您有多个 px.scatter 图形,则可以遍历它们,并将 px.scatter 图形中的每个跟踪添加到您的 subplots 对象的相应行和列。然后我们可以将每个 px.scatter 图形中的轴标题添加到 subplots 对象布局中。
我将使用tips 示例数据集来演示:
import plotly.express as px
from plotly.subplots import make_subplots
df = px.data.tips()
fig1 = px.scatter(df, x="total_bill", y="tip", color="smoker")
fig2 = px.scatter(df, x="total_bill", y="tip", color="day")
fig_subplots = make_subplots(rows=2, cols=1)
for trace in fig1.data:
fig_subplots.add_trace(
trace,
row=1, col=1
)
for trace in fig2.data:
fig_subplots.add_trace(
trace,
row=2, col=1
)
## x and y axies in fig_subplots["layout"] are called xaxis, xaxis2, ..., yaxis, yaxis2, ...
## here we are making the assumption you are stacking your plots vertically
def modify_axis_titles(fig_subplots, px_fig, nrow):
xaxis_name, yaxis_name = f"xaxis{nrow}", f"yaxis{nrow}"
fig_subplots['layout'][xaxis_name]['title'] = px_fig.layout['xaxis']['title']
fig_subplots['layout'][yaxis_name]['title'] = px_fig.layout['yaxis']['title']
for px_fig, nrow in zip([fig1, fig2],[1,2]):
modify_axis_titles(fig_subplots, px_fig, nrow)
fig_subplots.show()