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

R语言用Plotly复现ggplot条形图时遇genome_size_in_Mb找不到错误

问题描述

尝试用R语言的Plotly复现ggplot绘制的条形图以实现交互效果,但无法将y轴设置为genome_size_in_Mb,报错:Error in eval(expr, data, expr_env) : object 'genome_size_in_Mb' not found。当前Plotly代码生成的图表不符合预期。

数据集

dba <- structure(list(Subgroups = c("Jessenii", "fluorescens", "fluorescens", 
"gessardii", "gessardii", "fragi", "fragi"), `Species Name + Strain` = c("Pseudomonas umsongensis", 
"Pseudomonas fluorescens", "Pseudomonas extremaustralis", "Pseudomonas sp.", 
"Pseudomonas fluorescens", "Pseudomonas psychrophila", "Pseudomonas taetrolens"
), Strain = c("GO16", "SBW25", "DSM17835", "Ag1", "R8", "HA4", 
"LMG2336"), `refseq assembly` = c("GCF_008824165.1", "GCF_000009225.2", 
"GCF_900102035.1", "GCF_000006765.1", "GCF_000297195.3", "GCF_000282975.1", 
"GCF_900104825.1"), genome_size_in_Mb = c(7.4, 6.7, 6.7, 6.3, 
7, 5.2, 4.9), `chromosome number` = c("2", "1", "1", "1", "1", 
"-", "-"), `GC content` = c(59, 60.5, 60.5, 66.5, 61, 56.5, 58
), `Number of CDS genes` = c(6441, 5974, 6000, 5572, 6307, 4666, 
4360), `Genes number` = c(6698, 6154, 6228, 6708, 6440, 4823, 
4507)), row.names = c(NA, -7L), class = c("tbl_df", "tbl", "data.frame"
))

可用的ggplot实现代码

ggplot(
  data = dba,
  aes(x = forcats::fct_inorder(Strain),
      y = genome_size_in_Mb,
      fill = Subgroups)
) +
  geom_bar(
    position = "dodge",
    stat = "identity",
    width = 0.5
  ) +
  scale_x_discrete(guide = guide_axis(angle = 90)) +
  labs(title = "Genome Sizes Across Strains", x = "Strain", y = "Genome Size in Mb")

尝试的Plotly代码(效果不符合预期)

library(plotly)
library(dplyr)

fig1 <- dba
fig1 <- fig1 %>% count(Strain, Subgroups)
fig1 <- fig1 %>% plot_ly(x = ~Strain, y = ~n, color = ~Subgroups)

print(fig1)

问题原因

你使用count(Strain, Subgroups)对数据进行了聚合,这会丢失原数据中的genome_size_in_Mb字段,同时count生成的n是分组的计数,并非你需要的基因组大小数值,因此既会出现对象找不到的错误,也会生成错误的图表。

解决方案

直接使用原数据集,按照ggplot的逻辑构建Plotly条形图,保留genome_size_in_Mb作为y轴变量,同时设置并列分组和轴标签:

library(plotly)
library(dplyr)
library(forcats)

# 保持Strain的原始顺序,和ggplot一致
dba <- dba %>% mutate(Strain = fct_inorder(Strain))

# 构建Plotly交互条形图
fig1 <- plot_ly(
  data = dba,
  x = ~Strain,
  y = ~genome_size_in_Mb,
  color = ~Subgroups,
  type = "bar",
  width = 0.5,
  text = ~genome_size_in_Mb, # 悬停时显示数值
  hoverinfo = "text+x+color"
) %>%
  layout(
    barmode = "dodge", # 实现分组并列,对应ggplot的position="dodge"
    title = list(text = "Genome Sizes Across Strains"),
    xaxis = list(
      title = "Strain",
      tickangle = 90 # x轴标签旋转90度
    ),
    yaxis = list(title = "Genome Size in Mb")
  )

print(fig1)

代码说明

  1. 用fct_inorder(Strain)保持菌株的原始顺序,和ggplot行为一致。
  2. 指定type="bar"并设置barmode="dodge",实现分组并列的条形图效果。
  3. 直接使用~genome_size_in_Mb作为y轴变量,避免数据聚合导致的字段丢失。
  4. 添加悬停信息,增强交互体验,同时设置轴标签和标题,与ggplot的可视化效果对齐。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 12:24:52