0

Could anyone share a way of splitting the x-axis text "Cycling (CD4/CD8/Treg)" and "Other T (gdT/MAIT)" into 2 lines to avoid the messy overlapping axis text in my plot?

Thanks!

Here is my code.

df<- meta_data %>% 
  group_by(Timepoint, Patient) %>% 
  count(cell_type) %>% 
  mutate( pro = n/sum(n)) %>% 
  group_by(Timepoint, cell_type) %>% 
  summarise(.groups = "keep", mean = mean(pro), se = sd(pro)/sqrt(length(pro))) %>% 
  ggplot(aes(x = factor(cell_type, 
                        levels = c( "CD8 T",  "CD4 T" ,"Treg", "Cycling (CD4/CD8/Treg)", "Other T (gdT/MAIT)"  , "non_T" )
                        ),
             y = mean,
             group = Timepoint)) + # move the error bar into the middle of the bar plot
  geom_col(aes(fill = Timepoint),
           position = "dodge") +
  geom_errorbar(aes(ymin = mean - se,
                    ymax = mean + se),
                width=0.2,
                position = position_dodge(0.9),
                colour="black",
                alpha=0.9, 
                size=0.9)+
  theme(axis.title.x = element_blank(),       #remove the x title
        axis.title.y = element_blank(), 
        axis.text.x = element_text(vjust = 0.5, hjust=0, size = 16),
        legend.text = element_text(size=24),
        legend.title = element_text(size=16)
        ) +
  theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
        panel.background = element_blank(), axis.line = element_line(colour = "black"))

I tried adding "\n" in the middle of "Cycling (CD4/CD8/Treg)", but failed since the x-axis text is a factor. Looking forward to any solution.

E. Nygaard
  • 104
  • 6
  • I did try the way you said. It doesn't work. – tufeiyinjie Apr 20 '23 at 16:31
  • Aw. Sorry. My fault. That will not work via the `levels`. Using one of the options from [Add line break to axis labels and ticks in ggplot](https://stackoverflow.com/questions/20123147/add-line-break-to-axis-labels-and-ticks-in-ggplot) you could try `scale_x_discrete(labels = c("Cycling (CD4/CD8/Treg)" = "Cycling\n(CD4/CD8/Treg)"))` – stefan Apr 20 '23 at 16:45

0 Answers0