繁体   English   中英

使用ggplot2在框图中未对齐的点

[英]Misaligned points in boxplots using ggplot2

当我使用带有此数据集运行ggplot2代码时( 在此处下载 )...

ggplot(data=P4L_melt, aes(variable, y=value)) + geom_boxplot(aes(fill=Species), alpha=0.7, lwd=0.5, outlier.shape=NA) + geom_point(position=position_jitterdodge(jitter.width=0),aes(group=Species, colour=Species), alpha=0.5)

我得到这个情节: 在此处输入图片说明

看来还好。 如您所见,我们分为三组(红色,绿色,蓝色),各自的观察结果与盒图重叠。

但是,如果我们关注左下角(不存在红色组),则会看到蓝色和绿色点未对齐(在DC1,DC2和DC3中)。 如何编辑代码以解决此问题?

好像geom_boxplot和position_jitterdodge对待NA的方式有所不同...

这是一个(模糊的)解决方法:

1)在df中创建一列,指定点的x位置:

library(ggplot2)
P4L_melt <- read.table('P4L_melt.txt')

P4L_melt$x <- as.numeric(gsub('DC', '', P4L_melt$variable))
P4L_melt$variable <- factor(P4L_melt$variable, levels = paste('DC', unique(P4L_melt$x), sep=''))
P4L_melt$x[P4L_melt$Species=='A'] <- P4L_melt$x[P4L_melt$Species=='A'] - 0.25
P4L_melt$x[P4L_melt$Species=='C'] <- P4L_melt$x[P4L_melt$Species=='C'] + 0.25
P4L_melt$x[P4L_melt$Species=='B'&P4L_melt$variable%in%c('DC1', 'DC2', 'DC3')] <- P4L_melt$x[P4L_melt$Species=='B'&P4L_melt$variable%in%c('DC1', 'DC2', 'DC3')] - 0.2
P4L_melt$x[P4L_melt$Species=='C'&P4L_melt$variable%in%c('DC1', 'DC2', 'DC3')] <- P4L_melt$x[P4L_melt$Species=='C'&P4L_melt$variable%in%c('DC1', 'DC2', 'DC3')] - 0.05

2)使用该列作为geom_point中的x位置

ggplot(data=P4L_melt, aes(variable, y=value)) + 
  geom_boxplot(aes(fill=Species), alpha=0.7, lwd=0.5, outlier.shape=NA) + 
  geom_point(aes(x=x, group=Species, colour=Species), alpha=0.5) 

结果..

好的,这是另一种尝试,也许在顶部:)

1)安装最新的ggplot2版本:

install.packages('tidyverse')
library('tidyverse')

2)从我的github下载我的position-dodge2.r及其依赖项position-collide.r的修改版本

3)将这些文件放在项目的工作目录中,然后:

source('position-collide.R')
source('position-dodge2.R')

4)现在这段代码应该给你你想要的!

ggplot(data=P4L_melt, aes(variable, y=value)) +
  geom_boxplot(aes(fill=Species), alpha=0.7) +
  geom_point(aes(colour=Species), position=position_dodge2(width=0.75), alpha=0.5)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM