I am working on a project and trying to reproduce following plot.
Here is my attempt.
test<-data.frame(
x=factor(rep(1:3, each=20)),
y=runif(60)
)
p<-ggplot(test, aes(x=x, y=y,fill=x)) +
geom_boxplot(width=0.2) +
geom_dotplot(binaxis = "y")
p
But boxplot and dotplot are crowded together in my attempt. Any advice is appreciated.
You can nudge the position of geoms by using position = position_nudge(...)
. You can use this to offset the boxplot and dotplot in opposite directions. Example below:
library(ggplot2)
test<-data.frame(
x=factor(rep(1:3, each=20)),
y=runif(60)
)
ggplot(test, aes(x=x, y=y,fill=x)) +
geom_boxplot(width=0.2, position = position_nudge(x = -0.1)) +
geom_dotplot(binaxis = "y", position = position_nudge(x = 0.1))
#> `stat_bindot()` using `bins = 30`. Pick better value with `binwidth`.
Created on 2021-04-05 by the reprex package (v1.0.0)
I would use the position_nudge(x = 0, y = 0)
function. This allows you to translate elements of a plot in x and y. The function can be used as the position argument in the geom_xxxx()
functions. Such as by using geom_boxplot(..., position = position_nudge(x = -0.1))
which translates the boxplots 0.1 to the left.
library(tidyverse)
test<-data.frame(
x=factor(rep(1:3, each=20)),
y=runif(60)
)
p<-ggplot(test, aes(x=x, y=y,fill=x)) +
#Translate left
geom_boxplot(width=0.2, position = position_nudge(-0.1)) +
#Translate right
geom_dotplot(binaxis = "y", width = 0.2, position = position_nudge(x = 0.1))
p
#> `stat_bindot()` using `bins = 30`. Pick better value with `binwidth`.
Created on 2021-04-04 by the reprex package (v2.0.0)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.