When adding traces to fig=px.scatter() does it have to be added with fig.add_traces(go.Scatter())?
I ask this because it gets very confusing with the subtle differences, that are a PIA to remember (for me), between px.scatter and go.scatter. Also, is it better/more comprehensive to use one or the other?
I feel like I should be able to add the traces the same way the original ones were created? i.e., fig.add_traces(px.Scatter()). That would cut down on remembering all the inputs. Am I missing something?
here is my sample code:
df = pd.DataFrame({'x':[1,2,3,4],'y':[1,1,1,1],'z':[10,10,10,10],'custom':[30,30,30,30]})
df2 = pd.DataFrame({'x':[1,2,3,4],'y':[2,2,2,2],'z':[15,15,15,15],'custom':[40,40,40,40]})
fig = px.scatter(df,
x='x',
y='y',
size='z',
size_max=10,
custom_data=['custom'],
color_discrete_sequence=['red'],
)
fig.update_traces(
hovertemplate="<br>".join([
"x: %{x}",
"some custom data: %{custom_data[0]}",
])
)
fig.add_traces(go.Scatter( x=df2['x'],
y=df2['y'],
mode='markers',
customdata=df2['custom'],
marker=dict(size=7,
symbol='circle',
color='blue',
)))
fig.update_traces(
hovertemplate="<br>".join([
"x: %{x}",
"some custom data: %{customdata}",
])
)
fig.show()
Thanks!
Here is a plotly express only solution.
import pandas as pd
import plotly.express as px
df = pd.DataFrame({'x':[1,2,3,4],'y':[1,1,1,1],'z':[10,10,10,10],'custom':[30,30,30,30]})
df2 = pd.DataFrame({'x':[1,2,3,4],'y':[2,2,2,2],'z':[15,15,15,15],'custom':[40,40,40,40]})
fig = px.scatter(df,
x='x',
y='y',
size='z',
size_max=10,
hover_data=['custom'],
color_discrete_sequence=['red'],
)
fig2 = px.scatter(df2,
x='x',
y='y',
hover_data=['custom'],
color_discrete_sequence=['blue'],
)
fig2.update_traces(marker=dict(
size=7,
symbol='circle',
color='blue',
))
# Add all the traces from fig2 to fig
fig.add_traces(fig2.data)
fig.show()