0

In ggplot, I would like to label the y-axis on two lines, as in 1 line it is overlapping.

Here is the code:

myd<- data.frame( var1 = rep(c("Newly infected","Mortality","TDR level"),each=3), 
                     samp = rep(c("Scen1: blablabla blabla blabla bla","Scen2","Scen3"),3), 
                  V3 = c(3.5,2,NA,8,2,NA,4,5,NA)/1.5, V2 = c(3.5,2,NA,8,3,NA,4,4.3,NA), V1 = c(1.5,0.2,5,5,3,0.2,4,-5,2) ) 

# rshaping data to long form for ggplot2 
library(reshape2)
meltd<- melt(myd, id.vars=1:2) 
#meltd<- meltd[-which(is.na(meltd$value)),]

ggplot(meltd, aes(x = var1, y = value, fill = variable, label = paste0(round(value * 100, 1), "%"))) +
  geom_bar(stat = "identity", position = position_dodge(width = 0.6), width = 0.5) +
  facet_grid(samp ~ ., switch = "y", scales = "free_y", space = "free") +
  coord_flip() +
  scale_fill_manual("legend",values = c("V3" = "orange", "V2" = "red", "V1" = "blue", "Baseline" = "black")) +
  geom_text(aes(y = value + 0.4 * sign(value)), position = position_dodge(width = 0.6)) +
  theme_bw() +
  theme(
    legend.position = "none",
    strip.placement = "outside",
    #axis.title.x = element_blank(),
    axis.title.y = element_blank(),
    axis.text.y = element_text(colour="black"),
    strip.text.y = element_text(size = 12, colour = "black"))+
  ylab("Relative change (in %)")

Here is the output:

Blabla too long on the y-axis label

EDIT: by adding labeller=label_wrap_gen(width=6, multi_line=T) in the facet_grid(), it put on several lines. The problem is I want only 2 lines. See figure below: Blabla on more than 2 lines

Anthony Hauser
  • 659
  • 1
  • 6
  • 14

2 Answers2

2

Inside the facet_grid call use something like labeller=label_wrap_gen(width=6, multi_line=T)

bobbel
  • 1,983
  • 6
  • 21
1

You can just add a newline into your names like this:

myd<- data.frame( var1 = rep(c("Newly infected","Mortality","TDR level"),each=3), 
              samp = rep(c("Scen1: blablabla blabla \n blabla bla","Scen2","Scen3"),3), 
              V3 = c(3.5,2,NA,8,2,NA,4,5,NA)/1.5, V2 = c(3.5,2,NA,8,3,NA,4,4.3,NA), V1 = c(1.5,0.2,5,5,3,0.2,4,-5,2) ) 

Which results in a plot like this: enter image description here

You can automatically enter a \n after a specific number of characters in your names with something like this:

myd$samp = sapply(as.character(myd$samp), function(x){
  ifelse(nchar(x) > 15,
         paste0(substr(x,1,15),"\n",substr(x,16,nchar(x))),
         x)
})
Mojoesque
  • 1,166
  • 8
  • 15