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

在ggplot2中根据beta正负值设置数据点形状的报错问题

问题描述

我有如下数据集:

beta pval Category_name
0.5 0.005 One
-0.3 0.6 Two
0.2 0.03 Three
-0.1 0.7 Four

想要绘制以-log10(pval)为Y轴、Category_name为X轴的图形,要求beta为正值时使用形状24,负值时使用形状25,Y轴展示与pval相关的数据。

我编写的脚本如下:

library(ggplot2)
library(RColorBrewer)

colourCount <- length(unique(dup_categories_merged_allSNP$Category_name))
getPalette <- colorRampPalette(brewer.pal(9, "Set1"))

dup_categories_merged_allSNP$shape <- ifelse(dup_categories_merged_allSNP$beta > 0, 24, 25)

PheWAS_all <- ggplot(dup_categories_merged_allSNP, aes(x = Category_name, y = -log10(pval), shape = shape, colour = Category_name)) + 
geom_point(size = 2) +
  geom_jitter() +
  theme_classic() + 
  scale_colour_manual(values = getPalette(colourCount)) +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 0, size = 10),
        axis.title.x = element_blank(),
        legend.position = "none") + 
  labs(color = "Category_name", x = "", y = "-log10(pval)") +
  geom_hline(yintercept = -log10(3.65E-09), color = "darkmagenta", linetype = "dashed", size = 1, alpha = 0.5) +
  geom_hline(yintercept = -log10(0.000740457), color = "gray32", linetype = "dashed", size = 1, alpha = 0.5)

运行后出现错误:

Error in scale_f():! A continuous variable can not be mapped to shape.

补充说明:原图形、修改后的图形及数据子集见对应截图。

解决方案

错误根源在于ifelse生成的shape列是连续数值型变量,而ggplot的shape美学映射仅支持离散型变量(因子或字符类型)。只需将shape列转换为因子,并手动指定形状对应值即可解决问题。

修改后的代码如下:

library(ggplot2)
library(RColorBrewer)

colourCount <- length(unique(dup_categories_merged_allSNP$Category_name))
getPalette <- colorRampPalette(brewer.pal(9, "Set1"))

# 将shape列转为离散因子,用标签区分正负beta
dup_categories_merged_allSNP$shape <- factor(
  ifelse(dup_categories_merged_allSNP$beta > 0, "positive", "negative"),
  levels = c("positive", "negative")
)

PheWAS_all <- ggplot(dup_categories_merged_allSNP, aes(x = Category_name, y = -log10(pval), shape = shape, colour = Category_name)) + 
  geom_point(size = 2) +
  geom_jitter() +
  theme_classic() + 
  scale_colour_manual(values = getPalette(colourCount)) +
  # 手动绑定形状:正beta用24,负beta用25
  scale_shape_manual(values = c(24, 25)) +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 0, size = 10),
        axis.title.x = element_blank(),
        legend.position = "none") + 
  labs(color = "Category_name", x = "", y = "-log10(pval)") +
  geom_hline(yintercept = -log10(3.65E-09), color = "darkmagenta", linetype = "dashed", size = 1, alpha = 0.5) +
  geom_hline(yintercept = -log10(0.000740457), color = "gray32", linetype = "dashed", size = 1, alpha = 0.5)
关键修改点
  1. 将shape列从连续数值转换为离散因子,用"positive"/"negative"作为分组标签,逻辑更清晰
  2. 添加scale_shape_manual()函数,精准指定正负beta对应的形状24和25
  3. 既满足ggplot对shape映射变量类型的要求,又完全实现了需求中的形状区分逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 12:22:57