Ggplot: adjust y-axis label: put on two lines [duplicate]
Ggplot: adjust y-axis label: put on two lines [duplicate]
This question already has an answer here:
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:
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:
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
2 Answers
2
Inside the facet_grid call use something like labeller=label_wrap_gen(width=6, multi_line=T)
labeller=label_wrap_gen(width=6, multi_line=T)
Just change the width to the amount that fits.
width=20
works in this case.– Mojoesque
Aug 23 at 11:13
width=20
Thanks bobbel and Mojoesque it works ;).
– Anthony Hauser
Aug 23 at 11:14
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:
You can automatically enter a n
after a specific number of characters in your names with something like this:
n
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)
)
Thanks, but I want only 2 lines (see the edited version).
– Anthony Hauser
Aug 23 at 11:06