10

我非常喜欢箱线图,其中抖动点覆盖在箱线图上以表示实际数据,如下所示:

set.seed(7)
l1 <- gl(3, 1, length=102, labels=letters[1:3])
l2 <- gl(2, 51, length=102, labels=LETTERS[1:2]) # Will use this later
y <- runif(102)
d <- data.frame(l1, l2, y)

ggplot(d, aes(x=l1, y=y)) + 
  geom_point(position=position_jitter(width=0.2), alpha=0.5) +
  geom_boxplot(fill=NA) 

在此处输入图像描述

(当每个框中的数据点数量非常不同时,这些特别有用。)

当我也(隐式)使用position_dodge通过第二个变量分隔箱线图时,我想使用这种技术,例如

ggplot(d, aes(x=l1, y=y, colour=l2)) + 
  geom_point(position=position_jitter(width=0.2), alpha=0.5) +
  geom_boxplot(fill=NA)

在此处输入图像描述

但是,我不知道如何通过colour变量(此处为l2)来躲避这些点,并让它们抖动。

4

5 回答 5

7

这是一种手动执行抖动和闪避的方法。

# a plot with no dodging or jittering of the points 
dp <- ggplot(d, aes(x=l1, y=y, colour=l2)) + 
  geom_point(alpha=0.5) +
  geom_boxplot(fill=NA)

# build the plot for rendering
foo <- ggplot_build(dp)
# now replace the 'x' values in the data for layer 1 (unjittered and un-dodged points)
# with the appropriately dodged and jittered points
foo$data[[1]][['x']] <- jitter(foo$data[[2]][['x']][foo$data[[1]][['group']]],amount = 0.2)
# now draw the plot (need to explicitly load grid package)
library(grid)
grid.draw(ggplot_gtable(foo))
# note the following works without explicitly loading grid
plot(ggplot_gtable(foo))

在此处输入图像描述

于 2013-09-26T05:05:49.193 回答
4

我认为您不会喜欢它,但除了为这些点生成您自己的 x 值外,我从未找到解决此问题的方法。在这种情况下:

d$l1.num <- as.numeric(d$l1)
d$l2.num <- (as.numeric(d$l2)/3)-(1/3 + 1/6)
d$x <- d$l1.num + d$l2.num

ggplot(d, aes(l1, y, colour = l2)) + geom_boxplot(fill = NA) +
  geom_point(aes(x = x), position = position_jitter(width = 0.15), alpha = 0.5) + theme_bw()

在此处输入图像描述

这当然离理想还有很长的路要走,但很快就会成为常规。如果有人有替代解决方案,我会很高兴!

于 2013-09-26T03:26:32.400 回答
3

新的 position_jitterdodge() 适用于此。但是,它需要填充美学来告诉它如何对点进行分组,因此您必须指定手动填充才能获得未着色的框:

ggplot(d, aes(x=l1, y=y, colour=l2, fill=l2)) + 
  geom_point(position=position_jitterdodge(width=0.2), alpha=0.5) +
  geom_boxplot() + scale_fill_manual(values=rep('white', length(unique(l2))))
于 2015-07-21T15:00:43.897 回答
3

我正在使用更新版本的 ggplot2 (ggplot2_2.2.1.9000),我正在努力寻找一个适用于我自己的类似情节的答案。@John Didon 的回答对我产生了错误;Error in position_jitterdodge(width = 0.2) : unused argument (width = 0.2). 我以前的代码与 geom_jitter 一起工作,在下载更新版本的 ggplot2 后停止工作。这就是我在下面解决它的方法 -最小的大惊小怪的代码......

ggplot(d, aes(x=l1, y=y, colour=l2, fill=l2)) + 
  geom_point(position = position_jitterdodge(dodge.width = 1, 
                                             jitter.width = 0.5), alpha=0.5) +
  geom_boxplot(position = position_dodge(width = 1), fill = NA)

在此处输入图像描述

于 2018-05-04T16:07:29.830 回答
0

另一种选择是使用构面:

set.seed(7)
   l1 <- gl(3, 1, length=102, labels=letters[1:3])
   l2 <- gl(2, 51, length=102, labels=LETTERS[1:2]) # Will use this later
   y <- runif(102)
   d <- data.frame(l1, l2, y)

   ggplot(d, aes(x=l1, y=y, colour=l2)) + 
     geom_point(position=position_jitter(width=0.2), alpha=0.5) +
     geom_boxplot(fill=NA) +
     facet_grid(.~l2) +
     theme_bw()

抱歉,没有足够的积分来发布结果图表。

于 2015-06-12T21:32:10.267 回答