Home > Net >  Left and right align some of the tick labels in x-axis of a ggplot
Left and right align some of the tick labels in x-axis of a ggplot

Time:03-24

I have below ggplot

library(ggplot2)
library(scales) 
df <- data.frame("levs" = c("a long label i want to wrap",
                            "another also long label"),
                 "vals" = c(1,2))

p <- ggplot(df, aes(x = levs, y = vals))   
  geom_bar(stat = "identity")    
  coord_flip()   
  scale_x_discrete(labels = wrap_format(20))

With this I am getting following plot

enter image description here

I am wondering if I can left align and right align leftmost and rightmost tick labels (i.e. 0.0 and 2.0) respectively. Basically in my actual plot, I have big -negative and positive numbers at these two place and they are overflowing the plot area.

Any input is very helpful.

CodePudding user response:

You can specify different hjust() in theme()

Code

library(ggplot2)

ggplot(df, aes(x = levs, y = vals))   
  geom_bar(stat = "identity")    
  coord_flip()   
  scale_x_discrete(labels = wrap_format(20))  
  scale_y_continuous(breaks = seq(-20000, 20000, by = 10000))  
  theme(axis.text.x = element_text(hjust=c(0, 0.5,0.5,0.5, 1)))

Output

enter image description here

Data

df <- data.frame("levs" = c("a long label i want to wrap",
                            "another also long label"),
                 "vals" = c(-20000,20000))
  • Related