Black Lives Matter. Please consider donating to Campaign Zero's mission of ending police violence in America.
https://www.joincampaignzero.org

Many traces on same plot in plotly express

Hi all,

I saw in the documentation that it is possible to overlap on the same plot canvas different plots with plotly express, e.g.:

import plotly.express as px
import plotly.graph_objs as go

iris = px.data.iris()
fig = px.scatter(iris, x="sepal_width", y="sepal_length", color="species")
fig.add_trace(go.Bar(x=[1,2,3,4], y=[5,6,7,8]))
fig.show()

is there a way to add the second (third, forth…) plot by passing another px plot and not by calling a go plot?

By trying something like

import plotly.express as px
import plotly.graph_objs as go

iris = px.data.iris()
fig = px.scatter(iris, x="sepal_width", y="sepal_length", color="species")
fig.add_bar(iris.species, iris.sepal_length)

I get different errors depending on the second plot type chosen:

Invalid value of type 'pandas.core.series.Series' received for the 'alignmentgroup' property of bar

Thanks for any suggestion

Matteo

1 Like

This works for me:

import pandas as pd
import plotly_express as px

iris = px.data.iris()
fig = px.scatter(iris, x="sepal_width", y="sepal_length", color="species")
df = pd.DataFrame({
    'x':[1,2,3,4],
    'y':[5,6,7,8],})
fig2 = px.bar(df, x="x", y="y")
fig.add_trace(fig2.data[0])
fig.show()

cheers,
marc

Thanks! Seems obvious, works well!

Just a bit of context on what’s happening here… px.bar() returns a full go.Figure() object, which contains traces, whereas fig.add_trace() expects a trace.