After having searched the web for hours now, I am absolutely frustrated and confused on how to address subplots with plotly express
in Python .
My idea is to plot a line plot side-by-side with a scatter plot and a line plot and define the labels , hover data etc. individually + add shapes and text to them.
What I came up with so far, however, uses make_subplots
and only accepts traces. Hence, all formatting of the plotly express figures is being lost in the subplots!
I only found a way to change the axis limits of the individual subplots but not how to add a customized hover template, x-labels, y-labels, etc.
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")
Thank you very much in advance!
for t in fig1.data:
sub_fig.add_trace(t, row=1, col=1)
for t in fig2.data:
sub_fig.add_trace(t, row=1, col=2)
for s in fig1.to_dict()["layout"]["shapes"]:
sub_fig.add_shape(s)
for s in fig2.to_dict()["layout"]["shapes"]:
sub_fig.add_shape({**{"xref":"x2", "yref":"y2"}, **s})
sub_fig
df = pd.DataFrame({"year":np.tile(range(2010,2010+10),2), "total":np.random.randint(300,800,20), "type":np.repeat(["a","b"],10),
'activity_2011_2015':np.random.randint(0,600,20), 'activity_2016_2020':np.random.randint(0,600,20)})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.