I have created a chart with ggplot
.
I have set the width of each bar, but I also want to set the spacing between the bars to a certain value (I want to reduce the spacing marked in red to 0.1, for example)? I know there are options like position_dodge, but that does not seem to work in combination with coord_flip().
In this related post it was suggested to use theme(aspect.ratio = .2), but this does not allow to additionally set the specific width of the bars.
Are there any suggestions to achieve this?
Code:
library(ggplot2)
set.seed(0)
numbers <- runif(5, 0, 10)
names <- LETTERS[seq(1, 5)]
df <- cbind.data.frame(names, numbers)
ggplot(data = df, aes(x = names, y = numbers)) +
geom_bar(stat = "identity", fill = "blue", width = 0.30) +
coord_flip()
Example 2: Decrease Width and Increase Space between Bars. When we want to Decrease the Width of Bars and Increase Space between Bars, we simply have to use the width parameter to the geom_bar() function. Here we set the value of the width parameter as 0.40.
To set space between bars in Bar Plot drawn using barplot() function, pass the required spacing value for space parameter in the function call. space parameter is optional and can accept a single value or a vector to set different space between bars in the bar plot.
How can I increase the space between the bars in my bar plot? Set the width of geom_bar() to a small value to obtain narrower bars with more space between them. By default, the width of bars is 0.9 (90% of the resolution of the data).
I think the solution is in the combination of
width
argument of geom_bar()
(which fills the space reserved for a bar)aspect ratio
argument of theme()
, which squeezes the plot vertically, leading to 'small' bars.With the following code:
library(ggplot2)
## your data
set.seed(0)
numbers <- runif(5, 0, 10)
names <- LETTERS[seq(1, 5)]
df <- cbind.data.frame(names, numbers) ## corrected args
ggplot(data = df, aes(x = names, y = numbers)) +
geom_bar(stat="identity",
fill = "blue",
width=0.9) + ### increased
theme(aspect.ratio = .2) + ### aspect ratio added
coord_flip()
you get the following graph:
I personally prefer to use the ggstance
package to avoid messing around with coord_flip
. you need to switch your x and y
library(ggplot2)
library(ggstance)
ggplot(df, aes(x = numbers, y = names)) +
geom_colh(fill = "blue", width = 0.9)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With