Black Lives Matter. Please consider donating to Black Girls Code today.

Subplot with two different kind of charts sharing legend

It is possible to make two subplots share the same legend being one a Pie chart and the other a Bar chart?

Maybe I could do it with a callback(I have the chart in a dash solution)?

Thank you!

Yes, it is possible to have two traces share the same legend. In order to do so, you need to assign both traces to the same legendgroup.

This functionality is documented at https://plotly.com/python/legend/#grouped-legend.

Here is an example:

import plotly.graph_objects as go
from plotly.subplots import make_subplots

fig = make_subplots(
    rows=1, cols=2,
    column_widths=[0.5, 0.5],
    row_heights=[0.5],
    specs=[[ {"type": "pie"}, {"type": "bar"}]])

labels = ['Oxygen','Hydrogen','Carbon_Dioxide','Nitrogen']
values = [4500, 2500, 1053, 500]

fig.add_trace(go.Pie(
    labels=labels, 
    values=values,
    legendgroup="group",
    textinfo='percent+label'), 
    row=1, col=1)

fig.add_trace(go.Bar(
    x=labels,
    y=values,
    legendgroup="group"), 
    row=1, col=2)

fig.show()

Hope that helps!

Actually, that exemplify the problem I am talking about.

As you can see on the image, legend is different for both graphs. You have “trace 1” for Bar plot and instead of being related to the legend entries from the Pie chart, that would be what I would like it to be.

Ok, I think I understand what you mean.

Unfortunately, that specific behavior is not currently supported if one of the traces is a pie chart. I would encourage you to submit an issue to the plotly.py github repository if that is functionality you would like to see in the library.

However, for pairs of traces which do not include a pie chart, this is possible.

You can make sure both traces share the same legend group and then set showlegend=False on one one trace to hide its legend. This will result in the traces sharing legend items and is demonstrated in the second example documented at https://plotly.com/python/legend/#grouped-legend.

Thank you very much!