ggplot转plotly(ggplotly)后图例消失的问题及解决
ggplotly转换带分组图例的ggplot时图例消失的解决方案
在R环境中,使用ggplotly()将带有颜色、形状分组图例的ggplot图表转换为plotly格式时,会出现图例消失的问题。经排查,问题根源在于原ggplot代码中的guides()函数,移除该函数后,plotly图表的图例即可正常显示。以下是完整示例:
示例数据
library(scales) packageVersion("ggplot2") #> [1] '3.4.0' library(plotly) packageVersion("plotly") #> [1] '4.10.1' data <- data.frame( stringsAsFactors = FALSE, Level = c("Fast","Fast","Fast","Fast", "Fast","Fast","Slow","Slow","Slow", "Slow","Slow","Slow"), Period = c("1Year","3Month","1Year","3Month", "1Year","3Month","1Year","3Month", "1Year","3Month","1Year","3Month"), X = c(0.002,0.002,0.1,0.1,0.9,0.9, 0.002,0.002,0.1,0.1,0.9,0.9), Y = c(1.38,1.29,1.61,1.61,1.74,0.98, 1.14,0.97,1.09,1.1,0.94,0.58) )
含guides()的原ggplot代码
这段代码生成的ggplot图表显示正常,但转换为plotly后图例消失:
plt <- ggplot(data = data, aes(x = X, y = Y, shape = Period, color = Level)) + geom_point(alpha = 0.6, size = 3) + labs(x = " ", y = "Value") + scale_y_continuous(labels = number_format(accuracy = 0.1)) + guides(color = guide_legend(title = "Level", order = 1), shape = guide_legend(title = "Period", order = 2)) + theme(axis.text.x = element_text(angle = 90)) plt
转换后图例消失的plotly代码
运行以下代码,生成的plotly图表无图例:
ggplotly(plt, height = 500) %>% layout(xaxis = list(autorange = "reversed"))
修复后的代码
移除guides()函数后,重新生成ggplot再转换为plotly,图例即可正常显示。同时可通过layout()自定义图例标题:
plt2 <- ggplot(data = data, aes(x = X, y = Y, shape = Period, color = Level)) + geom_point(alpha = 0.6, size = 3) + labs(x = " ", y = "Value") + scale_y_continuous(labels = number_format(accuracy = 0.1)) + theme(axis.text.x = element_text(angle = 90)) plt2 ggplotly(plt2, height = 500) %>% layout( xaxis = list(autorange = "reversed"), legend = list( title = list(text = '(Period, Level)')) )
内容的提问来源于stack exchange,提问作者Tung
相关产品推荐
相关产品推荐

