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

为何ggplotly会移除ggplot2中geom_point的一个图例?如何修复?

ggplotly()移除ggplot2散点图其中一个图例的原因及修复方案

问题现象

用ggplot2绘制同时映射colour(对应ExpressionValue)和size(对应Coverage)的散点图时,能正常显示两个图例,但通过ggplotly()转换为交互式图表后,其中一个图例(通常是size图例)会消失。

原因

ggplotly在处理连续型变量的图例时,默认会做自动优化:当两个图例都是连续变量时,它会优先保留颜色图例,或者因布局逻辑自动隐藏其中一个,导致原本在ggplot2中显示的两个图例只剩一个。另外,若scale设置了limits但未同步调整ggplotly的图例参数,也可能触发这个问题。

修复方法

以下两种方案都能解决这个问题:

方案1:在ggplot2中强制指定双图例显示

通过guides()函数明确指定两个图例的类型,让ggplotly保留双图例的设置:

# 先构建ggplot对象
p <- ggplot(input, aes(x=CellType, y = GeneName, colour= ExpressionValue, size=Coverage)) +
  geom_point(alpha = 0.7) +
  scale_size_continuous(limits = c(0, 100)) +
  scale_color_gradientn(colours = c("#D9F2FE", "#C1E9FC", "#7ce8ff", "#55d0ff",'#00acdf','#0080bf'), 
                        limits = c(min(input$ExpressionValue), max(input$ExpressionValue))) +
  facet_wrap(~ virus, ncol =3)+
  theme_bw() +
  # 强制指定两个图例都显示
  guides(colour = guide_colorbar(), size = guide_sizebar())

# 转换为交互式图表
ggplotly(p)

方案2:在ggplotly中手动开启所有图例

遍历ggplotly生成的trace对象,强制设置showlegend = TRUE:

# 先构建ggplot对象并转换为ggplotly
p <- ggplot(input, aes(x=CellType, y = GeneName, colour= ExpressionValue, size=Coverage)) +
  geom_point(alpha = 0.7) +
  scale_size_continuous(limits = c(0, 100)) +
  scale_color_gradientn(colours = c("#D9F2FE", "#C1E9FC", "#7ce8ff", "#55d0ff",'#00acdf','#0080bf'), 
                        limits = c(min(input$ExpressionValue), max(input$ExpressionValue))) +
  facet_wrap(~ virus, ncol =3)+
  theme_bw()

ply <- ggplotly(p)

# 遍历所有trace,开启图例显示
ply$x$data <- lapply(ply$x$data, function(trace) {
  trace$showlegend <- TRUE
  trace
})

# 输出交互式图表
ply

输入数据示例

input <- data.frame(
  GeneID = rep("ENSG00000162896", 9),
  ExpressionValue = c(0.277122022, 0.453357839, 0.528442331, 
                      1.362933619, 0.832358131, 0.951361974, 0.073292538, 0.043776198, 0.062623433),
  Coverage = c(92.58126, 83.96996, 85.58937, 99.10806, 93.16097, 94.26496, 91.32948, 77.94179, 80.44060),
  CellType = c("All-Cells", "All-Cells", "All-Cells", "Epithelial", "Epithelial", "Epithelial", "Immune", "Immune", "Immune"),
  virus = c("fluA", "healthy", "SARS-CoV-2", "fluA", "healthy", "SARS-CoV-2", "fluA", "healthy", "SARS-CoV-2"),
  GeneName = rep("PIGR", 9),
  Secreted = rep(TRUE, 9)
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 06:42:08