How can I insert in subplots several treemaps created with express?

Hi all,

I have created a treemap constructor using express. It work like a charm - indeed, with the help of @Emmanuelle here: Change hovertext fields of a treemap in plotly express

I have built a function as a treemap builder which takes the values from a dictionary

def maparbol(df):

    subfig = px.treemap(df, path=['type','name'], values = datosgraficos[busqueda]['values'], 

                 width=datosgraficos[busqueda]['tamaño horizontal'], height=datosgraficos[busqueda]['tamaño vertical'],

                 title=datosgraficos[busqueda]['titulo'],

                        )

    return subfig

when I call it like fig = maparbol(df) it works like a charm

however, when I try to insert two of them in the same plot, using subplots, like so:

fig = make_subplots(rows=1, cols=2)
fig.add_trace(maparbol(df),row=1,col=1)

it returns a value error, like

ValueError:
    Invalid element(s) received for the 'data' property of
        Invalid elements include: [Figure({
    'data': [{'branchvalues': 'total',
              'domain': {'x': [0.0, 1.0], 'y': [0.0, 1.0]},
              'hovertemplate':

I have read all this thread and its derived links: https://github.com/plotly/plotly_express/issues/83

But I haven’t figure out what do I have to do in order to show two treemaps generated with express, side by side

What do I have to do in order to (convert?) a px figure into a go one for using subplots?

thanks in advance

@jlchulilla

You get that error because you started working directly with plotly express whithout having a background in plotly.graph_objects.

Plotly.py is a graphing library with the most solid logic behind it: a plotly figure consists in data, i.e. a list of traces, and the figure layout (if your figure is an animation it also contains the frames description). Plotly express is built on top of plotly.py, and consists in, let us say, functions whose args and keywords give a mixture of information on both the trace(s) to be plotted and the layout of the plot.

Plotly.express returns a figure. In order to see its components, just after defining it, print(fig.data), respectively print(fig.layout) to inspect them. Knowing how these components are defined, you can perform trace updates and/or layout updates to improve both the functionality and the plot aesthetics.

Now in your case, maparbol returns a figure. Hence it is not allowed to add it to a subplot, because, as its name says fig.add_trace adds a trace to a subplot. Since your subfig= maparbol(df) is a figure object you have to add the trace
subfig.data[0] to the subplot row=1, col=1, or by your code:

fig.add_trace(maparbol(df).data[0], row=1,col=1)
1 Like