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

2 Likes

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.

2 Likes

Thanks for all the replies!

So the “best” way is to create a figure (with px.bar, px.whatever…), extract the trace and add the trace to the first Figure object?

I’m just a little bit confused on the more standard method, considering also eventual development of the library

I don’t know if there’s a “best” way… they’re pretty equivalent :slight_smile: If you like the PX API then creating multiple figures that way and reassembling their traces is a fine way to go. If you want finer-grained control, you can build up a figure from graph objects, or pretty much anything in between.

1 Like

How is this in python? Anyone has idea?