Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
996 views
in Technique[技术] by (71.8m points)

r - Align axis label on the right with ggplot2

Consider the following

d = data.frame(y=rnorm(120), 
               x=rep(c("bar", "long category name", "foo"), each=40))

ggplot(d,aes(x=x,y=y)) + 
    geom_boxplot() + 
    theme(axis.text.x=element_text(size=15, angle=90))

plot with poorly aligned labels

The x-axis labels are aligned by the center of the label. Is it possible to automatically align on the right so that every label would end right below the graph?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is precisely what the hjust and vjust parameters are for in ggplot. They control the horizontal and vertical justification respectively and range from 0 to 1. See this question for more details on justifications and their values (What do hjust and vjust do when making a plot using ggplot?).

To get the labels the way you want you can use:

  • hjust = 0.95 (to leave some space between the labels and the axis)
  • vjust = 0.2 (to center them in this case)

ggplot(d,aes(x=x,y=y)) + geom_boxplot() + 
       theme(axis.text.x=element_text(size=15, angle=90,hjust=0.95,vjust=0.2))

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...