two labels in x axis

I am not being able to display the multi-axis level for the x-axis. I have read the solution in StackOverflow and I am trying to implement it. However, I am not being able to display the text outside of the plot limiting the y axis.

library(reprex)
library(ggplot2)
value<-(sample(x=1:5, size = 96, replace = TRUE))
person_id<- rep(paste("P", 1:24), each = 4)

cluster_id<- rep(paste("C", 1:12), each=8)
df<- data.frame(person_id, cluster_id, value)


p<- ggplot(df, aes(x = interaction(person_id, cluster_id), y = value))+geom_point(size = 4)+ geom_boxplot()+
  annotate(geom = "text", x = seq_len(24), y = -0.30, label = levels(df$person_id), size = 4) +
  annotate(geom = "text", x = 1.5 + 2 * (0:11), y = -0.45, label = levels(df$cluster_id), size = 5)+theme(axis.line = element_line(colour = "black"),panel.grid.major = element_blank(),panel.grid.minor = element_blank(),panel.border = element_blank(),panel.background = element_blank(), axis.title.x=element_blank(),axis.text.x=element_blank(),axis.ticks.x=element_blank())

p

[image]

# moving the annotate text outside the plot
p+coord_cartesian( ylim = c(1, 5), clip = "off")

[image]

  # theme(plot.margin=unit(c(1,1,3,1.2),"cm"))

I was able to solve this by using facet.

library(reprex)
library(ggplot2)
value<-(sample(x=1:5, size = 96, replace = TRUE))
person_id<- rep(paste("P", 1:24), each = 4)

cluster_id<- rep(paste("C", 1:12), each=8)
df<- data.frame(person_id, cluster_id, value)

ggplot(df, aes(x =person_id, y = value))+ 
  geom_boxplot(alpha = .4,  aes (fill = cluster_id, color = cluster_id, alpha = .4))+
  geom_point(aes(color = cluster_id, alpha = .4))+
  facet_wrap(vars(cluster_id), strip.position = "bottom", scales = "free_x", nrow =1)+ 
  theme(panel.spacing = unit(0, "lines"),
        strip.background = element_blank(),
        axis.line = element_line(colour = "grey"),
        panel.grid.major.y =element_line(colour = "grey"),
        strip.placement = "outside",
        axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5),
        panel.background = element_rect(fill = 'white', colour = 'white')
  )+labs(x="")+ theme(legend.position = "none") 

image

Created on 2021-07-12 by the reprex package (v1.0.0)

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.