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

ggplot中使用guide后ggplotly图例不显示的问题及解决

解决ggplot使用guide设置后ggplotly图例不显示的问题

当在ggplot中通过guides(fill = guide_legend(reverse = TRUE))设置图例反转后,调用ggplotly()转换为交互式图表时会出现图例消失的情况,但移除该guide设置后图例又能正常显示。

复现问题的代码:

library(plotly)
library(ggplot2)
library(dplyr)
diamonds %>% 
  group_by(cut,color) %>% 
  summarise(price = mean(price)) %>% 
  ggplot(aes(x=cut,y=price,fill= color))+
  geom_bar(stat='identity')  +  
  guides(fill = guide_legend(reverse = TRUE)) -> t
ggplotly(t) 

移除guide设置后正常显示的代码:

diamonds %>% 
  group_by(cut,color) %>% 
  summarise(price = mean(price)) %>% 
  ggplot(aes(x=cut,y=price,fill= color))+
  geom_bar(stat='identity') -> t
ggplotly(t) 

问题原因与解决方案:

这个问题是plotly 4.10.3版本的兼容性bug,将plotly包更新到最新版本即可解决——既能保留guides(fill = guide_legend(reverse = TRUE))的图例反转设置,又能让ggplotly正常显示图例。

更新plotly的命令:

install.packages("plotly")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 12:52:12