So I'm trying to combine two plots into one. I've made these plots with the plotly.express library rather than the plotly.graphs_objs.
Now, plotly suggests using: fig = make_subplots(rows=3, cols=1)
and then append_trace
or add_trace
However, this doesn't work for express objects since the append trace expects a single. trace. How can I add a express figure to a subplot? Or is this simply not possible. One option I've tried was fig.data[0]
but this will only add the first line/data entry. Rn my code looks like:
double_plot = make_subplots(rows=2, cols=1, shared_xaxes=True)
histo_phases = phases_distribution(match_file_, range)
fig = px.line(match_file,
x="Minutes", y=["Communicatie", 'Gemiddelde'], color='OPPONENT')
fig.update_layout(
xaxis_title="Minuten",
yaxis_title="Communicatie per " str(range) "minuten",
legend_title='Tegenstander',
)
double_plot.append_trace(fig.data, row=1, col=1)
double_plot.append_trace(histo_phases.data, row=2, col=1)
Thanks in advance.
CodePudding user response:
- your code sample does not include creation of data frames and figures. Have simulated
- it is as simple as adding each traces from figures created with plotly express to figure created with
make_subplots()
for t in fig.data:
double_plot.append_trace(t, row=1, col=1)
for t in histo_phases.data:
double_plot.append_trace(t, row=2, col=1)
full code
from plotly.subplots import make_subplots
import plotly.express as px
import pandas as pd
import numpy as np
df = px.data.tips()
double_plot = make_subplots(rows=2, cols=1, shared_xaxes=True)
# histo_phases = phases_distribution(match_file_, range)
histo_phases = px.histogram(df, x="total_bill")
match_file = pd.DataFrame(
{
"Minutes": np.repeat(range(60), 10),
"Communicatie": np.random.uniform(1, 3, 600),
"Gemiddelde": np.random.uniform(3, 5, 600),
"OPPONENT": np.tile(list("ABCDEF"), 100),
}
)
fig = px.line(match_file, x="Minutes", y=["Communicatie", "Gemiddelde"], color="OPPONENT")
fig.update_layout(
xaxis_title="Minuten",
yaxis_title="Communicatie per " str(range) "minuten",
legend_title="Tegenstander",
)
for t in fig.data:
double_plot.append_trace(t, row=1, col=1)
for t in histo_phases.data:
double_plot.append_trace(t, row=2, col=1)
double_plot