You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用R的plot_ly包add_pie函数时报object not found错误如何解决

问题原因

  • 参数传递错误:add_pie()的第一个入参默认是plotly图形对象,你将count()返回的统计结果直接放在第一个参数位,没有显式声明data =,导致plotly没有将该结果识别为绘图数据源,字段查找失败。
  • 布局配置错误:你需要1行2列的子图布局,但layout中grid参数配置为columns=1,就算解决参数问题也无法正常显示两个饼图。

修正后可运行代码

library(plotly)
library(dplyr) # count函数依赖dplyr包,需提前加载

results_demo_test <- 
structure(list(demo_residence = structure(c(1L, 1L, 1L, 2L, 1L, 
1L), .Label = c("Yes", "No"), class = c("ordered", "factor"
)), demo_gender = structure(c(1L, 1L, 2L, 2L, 1L, 2L), .Label = c("Male", 
"Female"), class = c("ordered", "factor"))), row.names = c(NA, -6L
), class = c("tbl_df", "tbl", "data.frame"))

fig <- plot_ly()

# 显式指定data参数承接统计结果
fig <- fig %>% add_pie(
  data = count(results_demo_test, demo_residence), labels = ~demo_residence, values = ~n, 
  name = "Residence", domain = list(row = 0, column = 0))

fig <- fig %>% add_pie(
  data = count(results_demo_test, demo_gender), labels = ~demo_gender, values = ~n, 
  name = "Gender", domain = list(row = 0, column = 1))

# 调整列数为2匹配子图数量
fig <- fig %>% layout(
  title = "Pie Charts with Subplots", showlegend = F,grid=list(rows=1, columns=2),
  xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
  yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE)
  )

fig

内容的提问来源于stack exchange,提问作者kwh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 10:45:05