I created a radar chart that displays data called zones. I am not able to make a callback function that returns the legends visible currently by user’s action on the legend. When user deselects legend item(s) the plot hides it well, but I need to capture what remains.
Essentially I am printing names of zones in display, later using it for data frame filters to display some analytics.
def create_radar_chart(metrics: Dict[str, List[float]], categories: List[str]) -> go.Figure:
fig = go.Figure()
fig.add_trace(go.Scatterpolar(
r=metrics['Baseline'],
theta=categories,
fill='toself',
name='Baseline',
line=dict(color='#808080'),
fillcolor='rgba(128, 128, 128, 0.2)'
))
colors = ['#00FFB8', '#4A9DFF', '#FF6B6B', '#FFD93D', '#6C63FF']
for i, (zone, values) in enumerate(metrics.items()):
if zone != 'Baseline':
color = colors[i % len(colors)]
fig.add_trace(go.Scatterpolar(
r=values,
theta=categories,
fill='toself',
name=zone,
line=dict(color=color),
fillcolor=f'rgba{tuple(list(int(color.lstrip("#")[i:i+2], 16) for i in (0, 2, 4)) + [0.4])}'
))
fig.update_layout(
width=500,
height=500,
polar=dict(
radialaxis=dict(
visible=True,
range=[0, max([max(vals) for vals in metrics.values()]) * 1.1]
),
bgcolor='rgba(0,0,0,0)'
),
showlegend=True,
paper_bgcolor='rgba(0,0,0,0)',
plot_bgcolor='rgba(0,0,0,0)',
font_color = '#7A7F8C',
legend_font_color = '#7A7F8C',
)
return fig
Metrics are the values for the plot by zone, Categories are the names
Here is a sample to reproduce:
import streamlit as st
import pandas as pd
from typing import Dict, List
import plotly.graph_objects as go
metrics = {
"Baseline": [60, 70, 80, 65, 90],
"Zone A": [75, 85, 70, 80, 95],
"Zone B": [65, 60, 75, 70, 85],
"Zone C": [55, 65, 85, 60, 80],
"Zone D": [80, 90, 70, 85, 88]
}
categories = ["Safety", "Infrastructure", "Resources", "Response Time", "Efficiency"]
def create_radar_chart(metrics: Dict[str, List[float]], categories: List[str]) -> go.Figure:
"""Create radar chart."""
fig = go.Figure()
fig.add_trace(go.Scatterpolar(
r=metrics['Baseline'],
theta=categories,
fill='toself',
name='Baseline',
line=dict(color='#808080'),
fillcolor='rgba(128, 128, 128, 0.2)'
))
colors = ['#00FFB8', '#4A9DFF', '#FF6B6B', '#FFD93D', '#6C63FF']
for i, (zone, values) in enumerate(metrics.items()):
if zone != 'Baseline':
color = colors[i % len(colors)]
fig.add_trace(go.Scatterpolar(
r=values,
theta=categories,
fill='toself',
name=zone,
line=dict(color=color),
fillcolor=f'rgba{tuple(list(int(color.lstrip("#")[i:i+2], 16) for i in (0, 2, 4)) + [0.4])}'
))
fig.update_layout(
width=500,
height=500,
polar=dict(
radialaxis=dict(
visible=True,
range=[0, max([max(vals) for vals in metrics.values()]) * 1.1]
),
bgcolor='rgba(0,0,0,0)'
),
showlegend=True,
paper_bgcolor='rgba(0,0,0,0)',
plot_bgcolor='rgba(0,0,0,0)',
font_color = '#7A7F8C',
legend_font_color = '#7A7F8C',
)
return fig
fig = create_radar_chart(metrics, categories)
fig.show()
4