【发布时间】:2022-01-10 01:52:59
【问题描述】:
在网上搜索了几个小时后,我对如何在 Python 中使用 plotly express 处理 subplots 感到非常沮丧和困惑。
我的想法是用散点图和线图并排绘制线图,并分别定义标签、悬停数据等+添加形状和文字。
然而,到目前为止我想出的是使用make_subplots 并且只接受跟踪。
因此,情节表达图形的所有格式都在子情节中丢失了!
我只找到了一种方法来更改各个子图的轴限制,但没有找到如何添加自定义悬停模板、x-labels、y-labels 等的方法。
import pandas as pd
import plotly.express as px
# CREATE 2 PLOTS with PLOTY EXPRESS ----------------------------------------------------
## fig 1 is a time series of two properties "type"
fig1 = px.line(df, x="year", y="total", color="type", title="layout.hovermode='x'")
fig1.update_traces(mode="markers+lines", hovertemplate=None)
fig1.update_layout(hovermode="x unified")
fig1.add_shape(type="line",
x0=2016,
y0=0,
x1=2016,
y1=800,
line=dict(
color="gray",
width=2,
dash="dot"))
## fig2 is a cross-plot of two properties "type"
fig2 = px.scatter(data_frame=df,
x='activity_2011_2015', y='activity_2016_2020',
#size='costs',
color='type')
# add x=y line
fig2.add_shape(type="line",
x0=0,
y0=0,
x1=600,
y1=600,
line=dict(
color="gray",
width=2,
dash="dot"))
# CREATE 1x2 SUBPLOTS ----------------------------------------------------
fig1_traces = []
fig2_traces = []
for trace in range(len(fig1["data"])):
fig1_traces.append(fig1["data"][trace])
for trace in range(len(fig2["data"])):
fig2_traces.append(fig2["data"][trace])
sub_fig = sp.make_subplots(rows=1, cols=2,
subplot_titles=['time series', 'cross-plot'],
horizontal_spacing=0.1)
for traces in fig1_traces:
sub_fig.append_trace(traces, row=1, col=1)
for traces in fig2_traces:
sub_fig.append_trace(traces, row=1, col=2)
## Address x axis and y axis range of first figure -----------------------------
sub_fig.update_layout(xaxis1 = dict(
tickmode = 'array',
range=[2015,2020],
tickvals = np.arange(2015, 2020, 1).tolist())
)
sub_fig.show()
sub_fig.write_html("sub_fig.html", include_plotlyjs="cdn")
- 如何处理子图中的单个图形及其元素?我想重新添加形状,添加自定义悬停数据并分别设置 X 和 Y 轴的格式,因为这些图没有相同的单位.. .
- 如果这不可行,能否以不同的方式重新创建此代码?我想要的只是两个情节,并排并与之互动......
非常感谢您!
【问题讨论】:
标签: python html plotly subplot plotly-python