Apricot
Apricot

Reputation: 3011

ggplot2 long x-axis variable names - re-aligning the plot

I am making a bar chart using ggplot2. The code is as follows:

 ggplot(rt5, aes(x = reorder(Retweet, -Freq), y = Freq, fill = Retweet)) +       geom_bar(stat = "identity") +
      xlab("Top 5 Retweets of KKRiders") +
      ggtitle("Top 5 Retweets of KKRiders \n first three days") + coord_flip() +
      scale_x_discrete(labels = function(x) str_wrap(x, width = 5)) +
      geom_text(aes(label=Freq), vjust = 1, colour = "white") + guides(fill = FALSE) +
      theme(axis.text.x = element_text(hjust = 0)) +
      theme(plot.title=element_text(size = rel(1.2), lineheight = 1, face = "bold"))

However since my x-axis variable labels are really long the chart looks like this.

enter image description here

How do i reduce the plot size and make my x-axis labels more readable? Can I reduce the size of the plot by half giving enough room for the x-axis labels?

The reproducible code is as follows:

  rt5 <- structure(list(Retweet = structure(c(1L, 2L, 3L, 4L, 5L), .Label = c(

 "RT @KKRiders On another note that makes 10 IPL victories in a row And we are hungry to #Go4More#KKR",
 "RT @KKRiders Yaaayy Were now the biggest IPL team on Instagram Thanks for  all your love Knight Riders #Go4More httptcoSamtCajmIk",
 "RT @RCBTweets Dazzling hitting from Surya Kumar Yadav He builds on Gambhirs 50 to hand @KKRiders a 7 wkt win in the big 2015 #PepsiIPL O",
 "RT @DabbooRatnani Congratulations @iamsrk @KKRiders Great Win last night and an amazing start to the #IPL season #AbRamAtEden",
 "RT @t2telegraph Little AbRam makes his #EdenGardens debut at @IPL 8s opening match between @KKRiders amp @mipaltan #IPL @iamsrk httptc"),
 class = "factor"), 
 Freq = c(334L, 203L, 153L, 149L, 100L)), .Names = c("Retweet", 
 "Freq"), row.names = c(1L, 2L, 3L, 4L, 5L), class = "data.frame")

Upvotes: 0

Views: 2303

Answers (1)

tonytonov
tonytonov

Reputation: 25608

Your labels look like that not because there's not enough space for them, but because there's a str_wrap usage with width=5 that forces line breaks. Instead use

scale_x_discrete(labels = function(x) str_wrap(x, width = 25)) +

and you'll be fine:

enter image description here

Upvotes: 2

Related Questions