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

r - ggplot2 : How to reduce the width AND the space between bars with geom_bar

I understand that one can change the width of a bar in geom_bar using the width argument. That does work, but then it creates a larger gap between the bars. Is there a way to manually push the bars closer to together? Should I be manipulating the axis somehow instead?

Here is an example, changing width to 0.3 on the right to get the desired bar width.

library(tidyverse)
library(gridExtra)

p1 <- ggplot(iris, aes(Species, Petal.Length)) + geom_bar(stat="summary")
p2 <- ggplot(iris, aes(Species, Petal.Length)) + geom_bar(stat="summary", width=0.3)
grid.arrange(p1,p2,nrow=1)

enter image description here

Note: I know this question is similar to this one, but the answer to closing the gap was not apparent.

How to change the space between bars in geom_bar?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

I would adjust the plot's aspect ratio, and have ggplot automatically assign the right width for the bars and the gap between them:

  ggplot(iris, aes(Species, Petal.Length)) + 
      geom_bar(stat="summary", width=0.4) +
      theme(aspect.ratio = 2/1)

Produces this:

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

...