可以结合position_jitter和position_dodge吗? [英] Possible to combine position_jitter with position_dodge?
问题描述
<$ c我已经变得非常喜欢在箱形图上叠加抖动点来表示实际数据的箱型图(2,51,...,2),其中,c(1,...,c)长度= 102,标签= LETTERS [1:2])#将在稍后使用
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,color = l2))+
geom_point(position = posi tion_jitter(width = 0.2),alpha = 0.5)+
geom_boxplot(fill = NA)
然而,我可以不知道如何通过 color
变量(这里, l2
)闪避点,并且抖动它们。 / p>
这是一种手动执行抖动和闪避的方法。
#一个没有闪避或抖动点的图
dp < - ggplot(d,aes(x = l1,y = y,color = l2))+
geom_point(alpha = 0.5)+
geom_boxplot(fill = NA)
#建立渲染图
foo< - ggplot_build(dp)
#现在用适当闪避和抖动的点替换第1层(未抖动和未闪避点)的数据中的'x'值
foo $ data [[1]] [['x ']] < - jitter(foo $ data [[2]] [['x']] [foo $ data [[1]] [['group']]],amount = 0.2)
# ñ ow绘制图(需要显式加载grid包)
library(grid)
grid.draw(ggplot_gtable(foo))
#注意以下工作,不显式加载grid
plot(ggplot_gtable(foo))
I've become quite fond of boxplots in which jittered points are overlain over the boxplots to represent the actual data, as below:
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)
(These are particularly helpful when there are very different numbers of data points in each box.)
I'd like to use this technique when I am also (implicitly) using position_dodge
to separate boxplots by a second variable, e.g.
ggplot(d, aes(x=l1, y=y, colour=l2)) +
geom_point(position=position_jitter(width=0.2), alpha=0.5) +
geom_boxplot(fill=NA)
However, I can't figure out how to dodge the points by the colour
variable (here, l2
) and also jitter them.
Here is an approach that manually performs the jittering and dodging.
# 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))
这篇关于可以结合position_jitter和position_dodge吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!