import pandas as pd
import plotly.graph_objects as go
import plotly.express as px
Dataset
For this post, we'll create a simple dataset with 2 columns: name
and value
:
data = {
'name': ['John', 'Anna', 'Peter', 'Linda'],
'value': [10, 20, 15, 25]
}
df = pd.DataFrame(data)
Plotly express
With plotly express
, it is very easy to create a radar chart.
You just need to call the px.line_polar()
function. Then we specify the r
(value) and theta
(label) parameters.
fig = px.line_polar(df, r='value', theta='name', line_close=True)
fig.update_traces(fill='toself')
fig.show()
fig.write_html("../../static/interactiveCharts/radarchart-plotly-express.html")
Let's see the results:
%%html
<iframe
src="../../interactiveCharts/radarchart-plotly-express.html"
width="800"
height="600"
title="Radar chart with plotly"
style="border:none">
</iframe>
Plotly graph objects
With plotly graph objects
, it is a bit more complex to create a radar chart. But it is also more flexible.
We use the add_trace()
function to add a trace to the figure. We specify the r
(value) and theta
(label) parameters.
fig = go.Figure()
fig.add_trace(
go.Scatterpolar(
r=df['value'],
theta=df['name'],
fill='toself'
)
)
fig.show()
fig.write_html("../../static/interactiveCharts/radarchart-plotly-object.html")
Let's see the results:
%%html
<iframe
src="../../interactiveCharts/radarchart-plotly-object.html"
width="800"
height="600"
title="Radar chart with plotly"
style="border:none">
</iframe>
Multiple radar charts
For displaying multiple radar charts, on the same figure, we just have to add multiple traces to the figure.
df['new_value'] = [20, 10, 25, 15]
fig = go.Figure()
fig.add_trace(
go.Scatterpolar(
r=df['value'],
theta=df['name'],
fill='toself'
)
)
fig.add_trace(
go.Scatterpolar(
r=df['new_value'],
theta=df['name'],
fill='toself'
)
)
fig.show()
fig.write_html("../../static/interactiveCharts/radarchart-plotly-object-2.html")
Let's see the results:
%%HTML
<iframe
src="../../interactiveCharts/radarchart-plotly-object-2.html"
width="800"
height="600"
title="Radar chart with plotly"
style="border:none">
</iframe>
Going further
This article explains how to create an interactive radar chart using plotly.
You might want to check how to create barplot with plotly and scatterplot with plotly.