使用ggplotly()转换ggplot地图可视化图表后图例消失的技术求助
解决ggplot转ggplotly后图例消失的问题
这个问题核心是你在连续填充色标(scale_fill_gradientn)里搭配了离散图例引导(guide_legend)——ggplot本身能兼容这种混合设置,但ggplotly对这类组合的支持不够友好,导致图例无法正常渲染。
下面是两种可行的解决方法:
方法1:使用匹配连续色标的图例引导
把guide_legend()替换为guide_colorbar(),它是专门为连续颜色刻度设计的,ggplotly能正确识别并显示:
# 修改后的ggplot代码 ggplotchange <- ggplot(data = map.world1, aes(x = long, y = lat, group = group, fill = happiness, text = paste("Country:", region, "<br>", "Happiness:", -happiness, "<br>", "Economy:", economy, "<br>", "Family:", family, "<br>", "Health:", -health, "<br>", "Freedom:", -freedom, "<br>", "Trust:", trust, "<br>", "Generosity:", generosity))) + geom_polygon() + scale_fill_gradientn(colors = ocean.curl(150)) + theme(panel.grid = element_blank(), axis.text = element_blank(), axis.title = element_blank(), axis.ticks = element_blank(), legend.title = element_blank(), plot.title = element_text(hjust = 0.5)) + labs(title = "Change from 2015 to 2022") + guides(fill = guide_colorbar(title = "")) # 替换为对应连续色标的引导 # 转换为ggplotly ggplotly(ggplotchange, tooltip = c("text"))
方法2:移除自定义guides,让scale自动生成图例
如果你不需要额外定制图例,直接去掉guides(fill = ...)这一行,scale_fill_gradientn会自动生成对应的颜色条图例,ggplotly也能正常显示:
ggplotchange <- ggplot(data = map.world1, aes(x = long, y = lat, group = group, fill = happiness, text = paste("Country:", region, "<br>", "Happiness:", -happiness, "<br>", "Economy:", economy, "<br>", "Family:", family, "<br>", "Health:", -health, "<br>", "Freedom:", -freedom, "<br>", "Trust:", trust, "<br>", "Generosity:", generosity))) + geom_polygon() + scale_fill_gradientn(colors = ocean.curl(150)) + theme(panel.grid = element_blank(), axis.text = element_blank(), axis.title = element_blank(), axis.ticks = element_blank(), legend.title = element_blank(), plot.title = element_text(hjust = 0.5)) + labs(title = "Change from 2015 to 2022") # 移除自定义guides行 ggplotly(ggplotchange, tooltip = c("text"))
注意:你的示例数据中happiness全为NA,实际测试时需要确保数据包含非NA的连续值,这样图例才能正常显示颜色刻度。
内容的提问来源于stack exchange,提问作者Conor
相关产品推荐
相关产品推荐

