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

如何在ggplot图例的HG002、HGDP00704上方添加EUR、AME标识

解决方案:修改图例标识 + 代码优化

一、实现带地区标识的表格式图例

要让图例中HG002上方显示EUR、HGDP00704上方显示AME,直接在scale_fill_manual中用换行符\n自定义标签即可,自动形成上下两行的表格布局:

修改绘图代码中的scale_fill_manual部分:

scale_fill_manual(
  values = c('#006BF7', '#BE90D4'),
  labels = c("EUR\nHG002", "AME\nHGDP00704")
)

二、代码优化建议

以下是针对原代码的优化点,让代码更简洁、符合现代R开发规范:

  • 替换停止维护的reshape2为tidyr的pivot_longer函数,更高效易用
  • 用管道符%>%串联数据操作,逻辑更连贯,减少冗余变量
  • 用rename函数直接重命名列,比修改names向量更直观
  • 无需手动将read_excel结果转成data.frame,返回的tibble可直接用于ggplot
  • 加载tidyverse包一次性引入多个常用工具包,减少重复调用

优化后的完整代码:

library(tidyverse)

# 读取Excel文件
excel2 <- read_excel("/media/mat/Extreme SSD/TheUniversityOfFerrara/2°Year/vcf_output-HG002againstHGDP00704-sites_R.xlsx")

# 数据整理:宽表转长表 + 重命名列
df <- excel2 %>%
  pivot_longer(cols = -record, names_to = "sample", values_to = "value") %>%
  rename(site_type = record)

# 若需指定site_type的显示顺序,取消注释并调整levels
# df <- df %>%
#   mutate(site_type = factor(site_type, levels = c("records", "SNPs", "indels", "multiallelic-sites", "others")))

# 绘制柱状图
ggplot(df, aes(x = site_type, y = value, fill = sample)) +
  geom_bar(stat = "identity", position = "dodge", width = .4) +
  theme_bw() +
  theme(
    plot.title = element_text(face = "bold.italic", hjust = 0.5),
    legend.position = "bottom",
    legend.title = element_blank(),
    # 可选:让图例文字居中对齐,上下行更整齐
    legend.text = element_text(hjust = 0.5)
  ) +
  scale_fill_manual(
    values = c('#006BF7', '#BE90D4'),
    labels = c("EUR\nHG002", "AME\nHGDP00704")
  ) +
  ggtitle('HG002-HGDP00704_Giraffe Variant Call')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 23:30:57