Assuming I have a toy model df
which lists the model
of the car and customer rating
of one car showroom.
JavaScript
x
9
1
CustomerID Model Cust_rating
2
3
1 Corolla A
4
2 Corolla B
5
3 Forester A
6
4 GLC C
7
5 Xterra A
8
6 GLC A
9
Using plotly express, I created pie charts of percentage of cars by model and by Cust_rating, respectively as two separate graphs:
JavaScript
1
4
1
import plotly.express as px
2
px.pie(df,names='Model',title='Proportion Of each Model')
3
px.pie(df,names='Cust_rating',title='Proportion Of each Rating')
4
Now, I want to create subplots, and all the ways of doing it using the documentation are throwing up errors:
JavaScript
1
3
1
ValueError: Trace type 'pie' is not compatible with subplot type 'xy'
2
at grid position (1, 1)
3
This is what I tried:
JavaScript
1
10
10
1
from plotly.subplots import make_subplots
2
import plotly.graph_objects as go
3
4
fig = make_subplots(rows=1, cols=2)
5
6
fig.add_trace(go.Pie(values=df['Model']), row=1, col=1)
7
fig.add_trace(go.Pie(values=df['Cust_rating']), row=1, col=2)
8
fig.update_layout(height=700, showlegend=False)
9
fig.show()
10
Advertisement
Answer
A pie chart in a graph object requires a pair of labels and values. You must also specify the plot type in the subplot. See this for an example of a subplot type.
JavaScript
1
20
20
1
from plotly.subplots import make_subplots
2
import plotly.graph_objects as go
3
4
fig = make_subplots(rows=1, cols=2, subplot_titles=("Model", "Rating"), specs=[[{'type': 'domain'},{'type': 'domain'}]])
5
6
fig.add_trace(go.Pie(labels=df['Model'].value_counts().index,
7
values=df['Model'].value_counts(),
8
legendgroup='model',
9
legendgrouptitle=dict(text='Model'),
10
),
11
row=1, col=1)
12
fig.add_trace(go.Pie(labels=df['Cust_rating'].value_counts().index,
13
values=df['Cust_rating'].value_counts(),
14
legendgroup='rating',
15
legendgrouptitle=dict(text='Rating')),
16
row=1, col=2)
17
18
fig.update_layout(height=400, width=600, showlegend=True)
19
fig.show()
20