0

Suppose that there is a dataframe which contains the following data:

Freq=c(0.15,0.25,0.6)
x=as.factor(c("Some long long long long text", "Another long long long long text", "But, this is really long long long long long text" ))
df<-data.frame(x=x, Freq=Freq)

And from this dataframe I would like to make a particular plot such as this one:

ggplot(df, aes(x=x, y=Freq)) + 
  geom_bar(stat="Identity", fill="dodgerblue3", width=.7) + 
  geom_text(aes(y = Freq, label = scales::percent(Freq), vjust = -0.5))+
  scale_y_continuous(labels=scales::percent, name ="", limits = c(0,0.7), expand = c(0,0))+
  scale_x_discrete(labels = levels(df$x), name="")

As you can see, the problem is that the labels of my discrete variable x, because are too long, do not appear nicely.

enter image description here

A very ad hoc solution that I could think, was to do this:

ggplot(df, aes(x=x, y=Freq)) + 
      geom_bar(stat="Identity", fill="dodgerblue3", width=.7) + 
      geom_text(aes(y = Freq, label = scales::percent(Freq), vjust = -0.5))+
      scale_y_continuous(labels=scales::percent, name ="", limits = c(0,0.7), expand = c(0,0))+
      scale_x_discrete(labels = c("Some long \n long long \n long text", "Another long \n long long \n long text", "But, this is \n really long long \n long long \n long text"), name="")

Which gives me this figure:

enter image description here

So, my question is whether there is another solution which does not require a manual intervention in the labels as I did.

msh855
  • 1,493
  • 1
  • 15
  • 36
  • 1
    The answers to [this SO question](http://stackoverflow.com/questions/37174316/how-to-fit-long-text-into-ggplot2-facet-titles/37174493#37174493) provide more automated ways to wrap strings. – eipi10 May 22 '16 at 06:48
  • as a side comment, sometimes `abbreviate` is useful. – Vincent Bonhomme May 22 '16 at 07:08

0 Answers0