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

R语言plotly绘制柱状图时text参数报错列长度不一致如何解决

问题原因

你代码的错误出在add_bars()的text参数里重复使用了公式标识~:你已经在text = ~开头声明了整段是公式映射,后面拼接变量时不需要再加~month_year、~lab的波浪号,重复的波浪号会让plotly解析映射时出现维度错位,最终报列长度不一致的错误。另外你代码末尾的管道符%存在笔误,也同步修正为%>%。

修正后的可运行代码

month_year<-structure(c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 
                          13L, 14L, NA), .Label = c("2020-Mar", "2020-Apr", "2020-May", 
                                                    "2020-Jun", "2020-Jul", "2020-Aug", "2020-Sep", "2020-Oct", "2020-Nov", 
                                                    "2020-Dec", "2021-Jan", "2021-Feb", "2021-Mar", "2021-Apr"), class = "factor")
First<-c(862, 19117, 121572, 588123, 882046, 1401836, 1065476, 813419, 
           834485, 916300, 1264637, 1369098, 2025535, 474664, 267236)
lab<-c("862", "19,117", "121,572", "588,123", "882,046", "1,401,836", 
         "1,065,476", "813,419", "834,485", "916,300", "1,264,637", "1,369,098", 
         "2,025,535", "474,664", "267,236")
re<-data.frame(month_year,First,lab)

p <- plot_ly() %>% 
  add_bars(re, x = ~month_year, y = ~First, name = "Brazil", 
           marker = list(color = "#3E5B84"), offsetgroup = 1,
           text = ~ paste("<b>Country:</b>", "Brazil", "<br><b>Date:</b>", month_year , "<br><b>Cases:</b>", lab),
           hovertemplate = paste('%{text}<extra></extra>')) %>%
  layout(
    showlegend=T,
    xaxis = list(title = "Date"),
    yaxis = list(title = "Brazil"),
    margin = list(b = 100),
    barmode = 'group',
    legend=list(title=list(text='<b> Country </b>'))
  )

p%>%
  config(modeBarButtonsToRemove = c('toImage',"zoom2d","toggleSpikelines","hoverClosestCartesian","hoverCompareCartesian","drawline","autoScale2d" ,"resetScale2d","zoomIn2d","zoomOut2d","pan2d",'select2d','lasso2d'))%>%
  config(displaylogo = FALSE)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 14:06:04