i have the code below that plot several pie charts with one bar chart using make_subplot while i assign each chart in the specs list the result is correct.
But if i try to make the specs parameter flexible the system crash and display the below error:
ValueError:
The ‘specs’ argument to make_subplots must be a 2D list of dictionaries with dimensions (2 x 3).
Received value of type <class ‘list’>: [[{‘type’: ‘pie’}, {‘type’: ‘pie’}, {‘type’: ‘pie’}, {‘type’: ‘pie’}, {‘type’: ‘pie’}, {‘type’: ‘pie’}], [{‘type’: ‘bar’}]]
code:
import plotly.graph_objs as go
from plotly.subplots import make_subplots
import plotly.express as px
lst = list(df.groupby('eventmohafaza_name'))
# here we want our grid to be 2 x 3
rows = 2
cols = 3
# continents are the first element in l
subplot_titles = [l[0] for l in lst]
# if i try the below line the system crash
specs = [[{"type": "pie"}]* cols * rows ,[{"type": "bar"}]]
# if i try the below line the system work correctly
#specs=[
# [{"type": "pie"},{"type": "pie"},{"type": "pie"}],
# [{"type": "pie"},{"type": "pie"},{"type": "bar"}],
#]
fig = make_subplots(
rows=rows,
cols=cols,
subplot_titles=subplot_titles,
specs=specs,
print_grid=True)
for i, l in enumerate(lst):
# basic math to get col and row
row = i // cols + 1
col = i % (rows + 1) + 1
# this is the dataframe for every continent
d = l[1]
fig.add_trace(go.Pie(labels=d["eventtype_name"],
values = d["number"],
hovertemplate = "%{label}: <br>Value: %{value} ",
showlegend=True,
textposition='inside',
rotation=90),
row=row,
col=col
)
group_event_groups = df.groupby([df['eventmohafaza_name'],df['eventtype_name']]).size().unstack()
for x in group_event_groups.columns:
fig.add_trace(go.Bar(name=str(x), x=group_event_groups.index, y=group_event_groups[x],showlegend=False), row=2, col=3)
fig.update_layout(height=800,width=800,title="Population by Continent", title_x=0.5)
fig.show()