I have these xy
data which I'm plotting using R
's ggplot2
geom_violin
:
library(dplyr)
library(ggplot2)
set.seed(1)
df <- data.frame(value = c(rnorm(500,8,1),rnorm(600,6,1.5),rnorm(400,4,0.5),rnorm(500,2,2),rnorm(600,7,0.5),rnorm(500,3,1),rnorm(500,3,1)),
age = c(rep("d3",500),rep("d8",600),rep("d24",400),rep("d3",500),rep("d24",600),rep("d8",500),rep("d24",500)),
group = c(rep("A",1500),rep("B",1100),rep("C",1000))) %>%
dplyr::mutate(time = as.integer(age)) %>%
dplyr::arrange(group,time) %>%
dplyr::mutate(group_age=paste0(group,"_",age))
df$group_age <- factor(df$group_age,levels=unique(df$group_age))
ggplot(df,aes(x=group_age,y=value,fill=age,color=age)) +
geom_violin(alpha=0.5) + geom_boxplot(width=0.1,aes(fill=age,color=age,middle=mean(value))) +
theme_minimal()
Which gives:
Now I'd like to change the x-axis
ticks
to have group
tick
label
s centered below each group
.
Assuming that:
ggplot_build(ggplot(df,aes(x=group_age,y=value,fill=age,color=age)) +
geom_violin(alpha=0.5) + geom_boxplot(width=0.1,aes(fill=age,color=age,middle=mean(value))) +
theme_minimal())$data[[2]]$xid
gives the x-axis
locations I used scale_x_discrete
specifying in breaks
the midpoints per each group
:
ggplot(df,aes(x=group_age,y=value,fill=age,color=age)) +
geom_violin(alpha=0.5) + geom_boxplot(width=0.1,aes(fill=age,color=age,middle=mean(value))) +
scale_x_discrete(breaks=c(2,4.5,6.5),labels=c("A","B","C")) + theme_minimal()
But this doesn't seem to be giving me the desired outcome:
Trying scale_x_continuous
instead of scale_x_discrete
gives this error:
Error: Discrete value supplied to continuous scale
Any idea how to get the x-axis
ticks
to be located at:
c(2,4.5,6.5)
With these labels
:
c("A","B","C")