FluffySheep1990
FluffySheep1990

Reputation: 441

Plotly Legend Item Names in Subplot Graph with Loop

I've created a subplot graph where I'm only showing the legend for the boxplot but the problem is that the legend items are appearing as 'trace 3', 'trace 4' and 'trace 5' which isn't very helpful.

I'm not able to use the category_orders or name commands within the code because neither of these work.

My code is:

import random 
import numpy as np
from plotly.subplots import make_subplots
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go

df = pd.DataFrame({"bedrooms": random.choices(range(1,10), k=200),
      "price": np.random.normal(loc = 500000, scale = 100000, size = 200).astype(int),
      "sqft_living": np.random.normal(loc = 2000, scale = 500, size = 200).astype(int)})

df["sqft_living_bins"] = pd.cut(df["sqft_living"], bins = [0, 1500, 2500, 6000], 
                                     labels = ["Small", "Medium", "Large"])

fig = make_subplots(cols = 2, rows = 2,
                   subplot_titles = ("Price ($)", "Sq Ft Living", "Number of Bedrooms", "All 3"))

fig.add_trace(go.Histogram(x = df["price"], showlegend = False), row = 1, col = 1)

fig.add_trace(go.Histogram(x = df["sqft_living"], showlegend = False), row = 1, col = 2)

fig.add_trace(go.Histogram(x = df["bedrooms"], showlegend = False), row = 2, col = 1)

for i, sqft in enumerate(df["sqft_living_bins"].unique()):
    df_plot = df[df["sqft_living_bins"] == sqft]
    
    fig.add_trace(go.Box(x = df_plot["bedrooms"], y= df_plot["price"], 
                         notched = True
                         #line = dict(color = colors[i]),
                         #name = "Small"
                         ), row = 2, col = 2)
 
fig.update_layout(boxmode = "group",
                 legend = dict(orientation = "h",
                               yanchor = "bottom",
                                xanchor = "right",
                                y = -0.13,
                                x = 1))

fig.show()

In the graph below I want the legend items to be replaced with 'Small', 'Medium' and 'Large'. Any help would be much appreciated.

enter image description here

Upvotes: 1

Views: 1033

Answers (1)

r-beginners
r-beginners

Reputation: 35115

Just like the color specification, the name can be made a target of the looping process in the list.

import random 
import numpy as np
from plotly.subplots import make_subplots
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go

df = pd.DataFrame({"bedrooms": random.choices(range(1,10), k=200),
      "price": np.random.normal(loc = 500000, scale = 100000, size = 200).astype(int),
      "sqft_living": np.random.normal(loc = 2000, scale = 500, size = 200).astype(int)})

df["sqft_living_bins"] = pd.cut(df["sqft_living"], bins = [0, 1500, 2500, 6000], 
                                     labels = ["Small", "Medium", "Large"])

fig = make_subplots(cols = 2, rows = 2,
                   subplot_titles = ("Price ($)", "Sq Ft Living", "Number of Bedrooms", "All 3"))

fig.add_trace(go.Histogram(x = df["price"], showlegend = False), row = 1, col = 1)

fig.add_trace(go.Histogram(x = df["sqft_living"], showlegend = False), row = 1, col = 2)

fig.add_trace(go.Histogram(x = df["bedrooms"], showlegend = False), row = 2, col = 1)

colors = ['orange','blue','green']
names = ['Large','Medium','Small']
for i, sqft in enumerate(df["sqft_living_bins"].unique()):
    df_plot = df[df["sqft_living_bins"] == sqft]
    fig.add_trace(go.Box(x = df_plot["bedrooms"], y= df_plot["price"], 
                             notched = True,
                             line = dict(color = colors[i]),
                             name = names[i]
                             ), row = 2, col = 2)
 
    fig.update_layout(boxmode = "group",
                     legend = dict(orientation = "h",
                                   yanchor = "bottom",
                                    xanchor = "right",
                                    y = -0.13,
                                    x = 1))

fig.show()

enter image description here

Upvotes: 2

Related Questions