使用Plotly结合DataFrame创建饼图子图遇错求助
解决Plotly饼图子图创建的ValueError问题
问题背景
现有汽车展厅数据集df:
CustomerID Model Cust_rating 1 Corolla A 2 Corolla B 3 Forester A 4 GLC C 5 Xterra A 6 GLC A
已通过Plotly Express实现独立饼图:
import plotly.express as px px.pie(df, names='Model', title='Proportion Of each Model') px.pie(df, names='Cust_rating', title='Proportion Of each Rating')
尝试合并为子图时触发错误:
ValueError: Trace type 'pie' is not compatible with subplot type 'xy' at grid position (1, 1)
尝试代码:
from plotly.subplots import make_subplots import plotly.graph_objects as go fig = make_subplots(rows=1, cols=2) fig.add_trace(go.Pie(values=df['Model']), row=1, col=1) fig.add_trace(go.Pie(values=df['Cust_rating']), row=1, col=2) fig.update_layout(height=700, showlegend=False) fig.show()
错误原因
- 子图类型不兼容:
make_subplots默认创建的是xy类型子图(笛卡尔坐标系),而饼图属于极坐标类轨迹,无法直接添加到xy子图中。 - 参数传递错误:
go.Pie的values参数需要传入类别对应的计数数值,直接传入原始类别列(如df['Model'])不符合要求。
修复方案
步骤1:指定子图类型为饼图
创建子图时通过specs参数声明每个子图的类型为pie,确保兼容饼图轨迹。
步骤2:预先统计类别计数
对Model和Cust_rating列做频次统计,得到每个类别的数量,再传递给go.Pie的names(类别名称)和values(计数)参数。
完整修复代码
from plotly.subplots import make_subplots import plotly.graph_objects as go import pandas as pd # 示例数据集 data = { 'CustomerID': [1,2,3,4,5,6], 'Model': ['Corolla','Corolla','Forester','GLC','Xterra','GLC'], 'Cust_rating': ['A','B','A','C','A','A'] } df = pd.DataFrame(data) # 统计各车型和评分的数量 model_counts = df['Model'].value_counts() rating_counts = df['Cust_rating'].value_counts() # 创建支持饼图的子图 fig = make_subplots( rows=1, cols=2, specs=[[{'type':'pie'}, {'type':'pie'}]], subplot_titles=['Proportion Of each Model', 'Proportion Of each Rating'] ) # 添加第一个饼图(车型占比) fig.add_trace( go.Pie(names=model_counts.index, values=model_counts.values), row=1, col=1 ) # 添加第二个饼图(评分占比) fig.add_trace( go.Pie(names=rating_counts.index, values=rating_counts.values), row=1, col=2 ) # 布局调整 fig.update_layout(height=500, width=800) fig.show()
补充说明
如果所有子图都是饼图,也可以直接用subplot_type='pie'简化创建:
fig = make_subplots( rows=1, cols=2, subplot_type='pie', subplot_titles=['Proportion Of each Model', 'Proportion Of each Rating'] )
内容的提问来源于stack exchange,提问作者JodeCharger100
相关产品推荐
相关产品推荐

