1

I have little experience with R and I have to create a graph with ggplot automatically from some datasets created with knime whose axis text (x=specie) can vary in number of letters. I have set a maximum width for this text (30). The problem is that at the end of this text I always have the expression "..., N = x". As it has two spaces in between, depending on the length of the text I can come across this:

........, N
        = x

Is there a way to force the expression "N = x" to always be on the same line?

My code is something like this:

library(ggplot2)
library(stringr)


ggplot(data, aes(fill=condition, y=value, x=specie)) + 
  geom_bar(color="black", position="stack", stat="identity", width = 4,)+
  scale_fill_manual(values = c("#990000", "#FF3300","#FFCC33","#FFFF99", "#FFFFFF","#99CC99") )+
  coord_flip()+
  scale_x_discrete(limits=data$specie, labels = function(x) str_wrap(str_replace_all(x, "foo" , " "),
                                                 width = 30))+
  labs(fill = " ", y= "Anteil Isolate (%)", x = "Programm")+ theme_minimal()+
  theme(legend.position = "bottom", legend.direction = "horizontal", legend.key.size = unit(0.5, "cm"), legend.text=element_text(size=12),
  legend.key.width = unit(0.5,"cm"), axis.text=element_text(size=12, color="black"), axis.title.y=element_blank(),
        axis.title=element_text(size=13, face="bold"), panel.grid.major.y = element_blank())+
  guides(fill = guide_legend(nrow = 1, byrow = TRUE,reverse=TRUE))
Gábor Bakos
  • 8,982
  • 52
  • 35
  • 52
CPR
  • 11
  • 1
  • I am not sure where the `N = x` comes from, but maybe you can `str_replace_all(x, "N = ", "N\u00a0=\u00a0")`. `\u00a0` is the [non-breaking space character](https://en.wikipedia.org/wiki/Non-breaking_space). – Gábor Bakos Nov 14 '20 at 07:17
  • I did not know that space character! Thanks a lot! It worked perfectly! :-) – CPR Nov 16 '20 at 05:32

1 Answers1

1

You can replace the spaces around the = sign with non-breaking spaces (\u00a0), which should prevent the line breaks at those places. Something like this should work: str_replace_all(x, "N = ", "N\u00a0=\u00a0")

Gábor Bakos
  • 8,982
  • 52
  • 35
  • 52