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。此外,您不需要在提供给 text 参数的函数内使用公式语法 (~),这就是导致错误的原因。
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>'))
)
推荐阅读
- angular - Chart.js - 如何放置标签而不是工具提示?
- vpn - odbc_connect():SQL 错误:[Sybase][ODBC 驱动程序][SQL Anywhere]找不到数据库服务器,SQL 状态 08001
- python - 在python的循环中更改循环变量
- ios - 如何在 PC Windows 上下载和运行 iOS 模拟器
- emacs - 将错误重定向到 org src 中的结果
- pandas - 根据日期和分组过滤熊猫数据框
- arrays - 为什么这个 LOOKUP 甚至可以工作,它是如何工作的?
- php - php sql用搜索查询多个条件?
- mysql - Yii2:为什么查询生成器不返回与 SQL 语句相同的结果?
- variables - 有没有办法在 VSCode 中拆分变量?