Nested legends on interactive stacked bar chart using plotly in python

Hi all, I need help creating a interactive stacked bar chart with nested legends using plotly in python. Specifically, I have a data frame with four columns: Phylum, Genus, Species, and abundances. I want the y axis to be the abundances, and the x axis to be each of the remaining columns, that is, one stacked bar chart that shows the phyla abundances, another for the genera, and one last one for the species. The most challenging part is to create a legend that fits them all. I mean, I need a nested legend that shows the Phyla as the legend group, then the genera within each Phylum, and then the species within each genera, and for instance, if you click on a Phylum, the three stacked bar charts will show the abundance of the phylum in the first stacked bar chart, the genera within that phylum in the second stacked bar chart, and the species within that genera for the third stacked bar chart. Is this even possible? Please see below a toy dataset to test this task:

data = {
    'Phylum': ['Ascomycota'] * 10 + ['Basidiomycota'] * 10,
    'Genus': ['Fusarium'] * 5 + ['Trichoderma'] * 5 + ['Cryptococcus'] * 5 + ['Agaricus'] * 5,
    'Species': ['oxysporum', 'graminearum', 'verticillioides', 'solani', 'niveum',
                'harzianum', 'atroviride', 'virens', 'longibrachiatum', 'hamatum',
                'neoformans', 'gattii', 'dendrorhous', 'bisporus', 'bispora',
                'muscaria', 'caesarea', 'subrufescens', 'virosa', 'phalloides'],
    'Abundance': [20, 15, 10, 5, 3] * 4  # Specify the relative abundances
}

# Create a DataFrame
df = pd.DataFrame(data)

Thank you so much in advance!

[quote=“Embudo gm-socrates, post:1, topic:83754, full:true”]
Hi all, I need help creating a interactive stacked bar chart with nested legends using plotly in python. Specifically, I have a data frame with four columns: Phylum, Genus, Species, and abundances. I want the y axis to be the abundances, and the x axis to be each of the remaining columns, that is, one stacked bar chart that shows the phyla abundances, another for the genera, and one last one for the species. The most challenging part is to create a legend that fits them all. I mean, I need a nested legend that shows the Phyla as the legend group, then the genera within each Phylum, and then the species within each genera, and for instance, if you click on a Phylum, the three stacked bar charts will show the abundance of the phylum in the first stacked bar chart, the genera within that phylum in the second stacked bar chart, and the species within that genera for the third stacked bar chart. Is this even possible? Please see below a toy dataset to test this task:

data = {
    'Phylum': ['Ascomycota'] * 10 + ['Basidiomycota'] * 10,
    'Genus': ['Fusarium'] * 5 + ['Trichoderma'] * 5 + ['Cryptococcus'] * 5 + ['Agaricus'] * 5,
    'Species': ['oxysporum', 'graminearum', 'verticillioides', 'solani', 'niveum',
                'harzianum', 'atroviride', 'virens', 'longibrachiatum', 'hamatum',
                'neoformans', 'gattii', 'dendrorhous', 'bisporus', 'bispora',
                'muscaria', 'caesarea', 'subrufescens', 'virosa', 'phalloides'],
    'Abundance': [20, 15, 10, 5, 3] * 4  # Specify the relative abundances
}

# Create a DataFrame
df = pd.DataFrame(data)

Thank you so much in advance!
[/quote]

Hello, @Embudo
I can see your post and I give you some ways to solve your query. Please see below and follow the information.

I can help you get started with the basic structure of the stacked bar charts for each category (Phylum, Genus, Species) using Plotly in Python. Here’s a simplified example of how you might approach it:

import plotly.graph_objects as go
import pandas as pd

Your data

data = {
‘Phylum’: [‘Ascomycota’] * 10 + [‘Basidiomycota’] * 10,
‘Genus’: [‘Fusarium’] * 5 + [‘Trichoderma’] * 5 + [‘Cryptococcus’] * 5 + [‘Agaricus’] * 5,
‘Species’: [‘oxysporum’, ‘graminearum’, ‘verticillioides’, ‘solani’, ‘niveum’,
‘harzianum’, ‘atroviride’, ‘virens’, ‘longibrachiatum’, ‘hamatum’,
‘neoformans’, ‘gattii’, ‘dendrorhous’, ‘bisporus’, ‘bispora’,
‘muscaria’, ‘caesarea’, ‘subrufescens’, ‘virosa’, ‘phalloides’],
‘Abundance’: [20, 15, 10, 5, 3] * 4
}

Create a DataFrame

df = pd.DataFrame(data)

Create a figure with subplots

fig = make_subplots(rows=3, cols=1, shared_xaxes=True)

Add traces for Phylum, Genus, and Species

for phylum in df[‘Phylum’].unique():
df_phylum = df[df[‘Phylum’] == phylum]
fig.add_trace(go.Bar(x=df_phylum[‘Genus’], y=df_phylum[‘Abundance’], name=phylum), row=1, col=1)

for genus in df[‘Genus’].unique():
df_genus = df[df[‘Genus’] == genus]
fig.add_trace(go.Bar(x=df_genus[‘Species’], y=df_genus[‘Abundance’], name=genus), row=2, col=1)

for species in df[‘Species’].unique():
df_species = df[df[‘Species’] == species]
fig.add_trace(go.Bar(x=[species], y=df_species[‘Abundance’].sum(), name=species), row=3, col=1)

Update layout for a stacked bar chart

fig.update_layout(barmode=‘stack’)

Show the figure

fig.show()

This code will create three stacked bar charts, one for each category. However, it won’t have the nested legend functionality you’re looking for. For that, you might need to explore Plotly’s JavaScript library or consider using a different visualization library that supports this level of interactivity.

Best Regard,
ryan1969