r-文本参数导致条形图中出现错误



我试图用下面的代码创建绘图条形图,但我得到了不同大小的列的错误。文本似乎有不同的大小,但为什么。

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)  

发生了两件事。首先,re被解析为绘图对象而不是数据帧,因为add_bars的数据参数是可选的。绘图之所以有效,是因为它引用了外部向量,而不是提供的df。此外,在提供给文本参数的函数中不需要公式语法(~(,这就是导致错误的原因。

p <- plot_ly() %>% 
add_bars(data=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>'))
)

最新更新