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

如何在ggplot中对字母数字混合的x轴按数值重新排序?

解决方法

问题出在peptide是字符串类型,ggplot默认按字母顺序排序。要实现数值顺序,需要提取字符串中的数字部分,以此为依据重新排序并转换为因子。

方法一:使用forcats和stringr包简化处理

修改你的函数,在数据过滤后添加因子排序逻辑:

plot <- function(date, gene, DM) {
  all_concats %>% 
    filter(date_plate_reading == date & gene_name == gene & DM_mm == DM) %>%
    # 提取peptide中的数字,按数值排序转换为因子
    mutate(peptide = forcats::fct_reorder(
      peptide, 
      as.numeric(stringr::str_extract(peptide, "\\d+"))
    )) %>%
    ggplot(aes(peptide, peptide_reading_total_sem)) + 
    geom_point() + 
    theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) +
    labs(x="peptide", y = "Standard mean error") +
    ggtitle(paste(gene, date)) # 合并标题参数,修复原函数的语法问题
}
  • stringr::str_extract(peptide, "\\d+"):提取peptide名称中的所有数字字符
  • forcats::fct_reorder():将peptide转换为因子,并按照提取出的数值排序

方法二:手动排序并设置因子水平(无需forcats)

如果不想额外依赖forcats包,可以手动处理:

plot <- function(date, gene, DM) {
  # 过滤并提取排序用的数值
  filtered_data <- all_concats %>% 
    filter(date_plate_reading == date & gene_name == gene & DM_mm == DM) %>%
    mutate(peptide_num = as.numeric(stringr::str_extract(peptide, "\\d+"))) %>%
    arrange(peptide_num)
  
  # 设置因子水平为排序后的顺序
  filtered_data$peptide <- factor(filtered_data$peptide, levels = filtered_data$peptide)
  
  ggplot(filtered_data, aes(peptide, peptide_reading_total_sem)) + 
    geom_point() + 
    theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) +
    labs(x="peptide", y = "Standard mean error") +
    ggtitle(paste(gene, date))
}

注意事项

  1. 确保已安装并加载stringr包(若用方法一还需forcats):
    install.packages(c("stringr", "forcats"))
    library(stringr)
    library(forcats)
    
  2. 原函数中ggtitle(gene, date)存在语法错误,ggtitle仅接受一个字符串参数,需用paste()合并两个变量。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 09:43:11