使用plotly绘制交互式ggplot图时geom_line()不显示无报错如何解决
问题成因
该问题是ggplotly转换折线图时,自定义tooltip的text参数和折线的分组逻辑冲突导致的:
geom_point本身不需要多观测分组,每个点对应一条单独的观测记录,和你自定义的text映射一一匹配,所以运行正常。geom_line需要同分组下至少2个连续观测才能绘制线条,你虽然给geom_line指定了color=country(颜色映射默认会生成对应分组),但全局aes里的text参数会被ggplotly优先识别为分组依据,每个text对应单条年度观测,拆分后每个分组仅1个数据点,无法生成线条,因此出现空白画布且无报错。- 补充:你提供的代码中
mutate(gdpPercap=round(gdpPercap,0))%存在笔误,少了管道符的后半段,需修正为%>%。
修复方案
可任选以下两种方案解决:
方案1:显式指定分组映射
直接在全局aes中添加group=country,强制按国家分组绘制折线,优先级高于text的自动分组:
library(tidyverse) library(plotly) library(gapminder) data1 <- gapminder %>% filter(country == "Cuba") data2 <- gapminder %>% filter(country == "Haiti") data3 <- gapminder %>% filter(country == "Jamaica") data4 <- gapminder %>% filter(country == "Dominican Republic") data_all<- bind_rows(data1,data2,data3,data4) data_ts<- data_all %>% select (-continent, -lifeExp, -pop) p <- data_ts %>% mutate(gdpPercap=round(gdpPercap,0)) %>% mutate(text = paste("Country: ", country, "\nGdp per capita: ", gdpPercap, sep="")) %>% # 新增group=country显式指定分组 ggplot(aes(x=year,y=gdpPercap, text=text, group=country, color=country)) + geom_line() + labs( title = "加勒比地区人均GDP走势", subtitle = "数据来源:gapminder", x = "年份", y = "人均GDP" ) + theme_minimal() + theme(legend.position="none") ggplotly(p, tooltip="text")
方案2:将text映射移动到散点图层
如果需要同时展示折线和点悬浮提示,可保留geom_point,将text参数从全局aes移到geom_point的独立映射中,不影响折线图层的分组逻辑:
p <- data_ts %>% mutate(gdpPercap=round(gdpPercap,0)) %>% ggplot(aes(x=year,y=gdpPercap, color=country)) + geom_line() + # text仅映射到散点图层 geom_point(aes(text = paste("Country: ", country, "\nGdp per capita: ", gdpPercap, sep=""))) + labs( title = "加勒比地区人均GDP走势", subtitle = "数据来源:gapminder", x = "年份", y = "人均GDP" ) + theme_minimal() + theme(legend.position="none") ggplotly(p, tooltip="text")
内容的提问来源于stack exchange,提问作者Patrick Stephenson
相关产品推荐
相关产品推荐

