I am using R and gglot only for a short time, so I am very grateful for any help! Since I like to use the secondary y-axis to display my mean values with breaks, facet_wrap has become only limitedly suitable to display the three plots side by side. So I used the library "cowplot" to manage that.
In order to keep the gray heading field - as in other graphs - I applied a facet_wrap to the single graph after all. But the y-axis label moves over the y-ticks label. Neither via margin, nor border or otherwise I manage to push the y-axis label to the outside.
Here is an example code:
set.seed(42) ## for sake of reproducibility
n <- 6
dat_A <- data.frame(id=1:n,
date=seq.Date(as.Date("2020-12-26"), as.Date("2020-12-31"), "day"),
group=rep(LETTERS[1:1], n/2),
age=sample(18:30, n, replace=TRUE),
type=factor(paste("type", 1:n)),
x=rnorm(n))
dat_B <- data.frame(id=1:n,
date=seq.Date(as.Date("2020-12-26"), as.Date("2020-12-31"), "day"),
group=rep(LETTERS[2:2], n/2),
age=sample(18:30, n, replace=TRUE),
type=factor(paste("type", 1:n)),
x=rnorm(n))
p1 <- ggplot(dat_A, aes(x=x, y=age, fill=group))+
geom_boxplot()+
geom_hline(aes(yintercept = age), linetype = "dashed")+
geom_jitter(alpha = .4)+
facet_wrap(~group, scales = "free")+
scale_y_continuous(limits = c(10, 30), expand = expansion(mult = c(.05, .05)), sec.axis = sec_axis(~ ., labels = scales::number_format(accuracy = 0.1), breaks = dat_A$age))+
guides(fill=FALSE)+
theme_bw(base_size = 9)+
labs(
y = expression(~bold(age)~'in a'),
color = NULL)+
theme(
text = element_text(family="Arial", size=9),
plot.margin = unit(c(0,.7,0,0), "cm"), # c(top, right, bottom, left)
axis.title.x = element_blank(),
legend.position = "none"
)
p2 <- ggplot()+
geom_point(aes(x, age), dat_B)+
facet_wrap(~group, scales = "free")+
labs(
y = expression(~bold(age)~'in a'),
color = NULL)+
theme(
plot.margin = unit(c(0,.7,0,0), "cm"), # c(top, right, bottom, left)
axis.line.x = element_blank()
)
library(cowplot)
plot_grid(p1, p2, p1, align = "h", nrow = 1, ncol = 3, rel_widths = c(22/100, 39/100, 39/100),
labels = c("A", "B", "C"),
label_size = 9,
label_fontfamily = "Cambria", ## emf seems to overwrite "fontfamily"
label_fontface = "bold",
label_colour = NULL,
label_x = -0.03,
label_y = 1 #0.05
)
Maybe interesting for some, otherwise the question can be deleted. For me it is solved.
Thanks Malte