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
509 views
in Technique[技术] by (71.8m points)

r - Spacing between boxplots in ggplot2

I have been working with ggplot2 a lot over the past few weeks and was wondering if anyone could help me solve this problem I am having.

When I plot my boxplot my boxes are touching each other. I would like them to have a little bit of space between them. Is there a way to accomplish this? I am sure there is and I am just not seeing it.enter image description here

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Let's borrow the reproducible example provided by Kevin Ushey in this question:

set.seed(123)
dat <- data.frame( 
  x=rep( c(1, 2, 3, 4), times=25 ),
  y=rnorm(100), 
  gp=rep(1:2, each=50) 
)

p <- ggplot(dat, aes(x=factor(x), y=y))
p + geom_boxplot(aes(fill = factor(gp))) #example 1

enter image description here

Then, following the advice of Arun, I tested the (position = position_dodge(.)) but with geom_boxplot instead of geom_bar, and it worked.

In this case, it was not necessary to change the boxes width.

So, changing the last line of the above code to:

p + geom_boxplot(aes(fill = factor(gp)),position=position_dodge(1))

did the trick.

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

1.4m articles

1.4m replys

5 comments

56.9k users

...