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

ggplot绘制Violin plot异常:未正确展示Membrane Intensity数据分布

解决ggplot小提琴图未正确展示数值分布的问题

问题说明

我使用ggplot基于数据框绘制小提琴图时,生成的图形未正确展示每组Membrane Intensity的数值分布——各组图形高度相似,看起来像是统计了每组数据点的数量而非实际数值的分布情况。

原代码

library(tidyverse)
library(ggplot2)
library("readxl")
read_excel("C:/Users/Jacob/Desktop/School/Gatlin rotation/Data Analysis/2.24.23 ImpB - P150.xlsx")
adjIntDen <- read_excel("C:/Users/Jacob/Desktop/School/Gatlin rotation/Data Analysis/2.24.23 ImpB - P150stuff.xlsx", sheet = "Sheet2")
area <- read_excel("C:/Users/Jacob/Desktop/School/Gatlin rotation/Data Analysis/2.24.23 ImpB - P150stuff.xlsx", sheet = "Sheet3")
adjIntDen <- data.frame(adjIntDen)
colnames(adjIntDen)[1] = "Membrane Intensity"
colnames(adjIntDen)[4] = "Time(m)"
adjIntDen <- drop_na(adjIntDen)
adjIntDen$`Membrane Intensity` <- as.numeric(adjIntDen$`Membrane Intensity`)
adjIntDen <- drop_na(adjIntDen)
intDen <- ggplot(adjIntDen, aes(x="Time(m)", y="Membrane Intensity", fill = Type)) + 
  geom_violin(trim = FALSE)+
  geom_dotplot(binaxis='y', stackdir = 'center', dotsize = 1)
  
              
intDen

问题根源

核心错误在于ggplot的美学映射(aes)中使用了双引号包裹变量名:

  • x="Time(m)"和y="Membrane Intensity"会让ggplot把这两个字符串当成固定值,而非数据框中的列名。这就导致所有数据都被映射到同一个x类别下,无法按Time(m)和Type分组计算数值分布,最终小提琴图的形态完全一致。

修正方案

去掉变量名的双引号,对于含空格的列名,用反引号`包裹即可。同时给geom_dotplot添加group=Type参数,确保点按分组堆叠展示:

library(tidyverse)
library(ggplot2)
library(readxl)

# 读取并预处理数据(保留原有逻辑)
adjIntDen <- read_excel("C:/Users/Jacob/Desktop/School/Gatlin rotation/Data Analysis/2.24.23 ImpB - P150stuff.xlsx", sheet = "Sheet2")
adjIntDen <- data.frame(adjIntDen)
colnames(adjIntDen)[1] <- "Membrane Intensity"
colnames(adjIntDen)[4] <- "Time(m)"
adjIntDen <- drop_na(adjIntDen)
adjIntDen$`Membrane Intensity` <- as.numeric(adjIntDen$`Membrane Intensity`)
adjIntDen <- drop_na(adjIntDen)

# 修正美学映射
intDen <- ggplot(adjIntDen, aes(x = `Time(m)`, y = `Membrane Intensity`, fill = Type)) + 
  geom_violin(trim = FALSE)+
  geom_dotplot(binaxis='y', stackdir = 'center', dotsize = 1, group = Type)

intDen

补充说明

  1. 当列名包含空格、特殊字符或与R保留字重名时,必须用反引号包裹,否则R无法识别为数据列。
  2. geom_dotplot的group参数会强制按指定分组独立计算点的堆叠位置,避免不同组的点混叠在一起,提升图表可读性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 14:47:23