I am trying to create a 2-factor plot where I can increase the distance between categories (dog vs. cat) WITHOUT affecting the padding between bars or width of the bars. This has been a whack-a-mole game -- I only seem to be able to change this distance by decreasing the width of the bar or padding, which I don't want to do. Any help is much appreciated. Reprex below...
sex <- c('f','m','f','m')
pet <- c('cat', 'cat', 'dog', 'dog')
mean <- c(4, 5, 4, 5)
df <- data.frame(sex, pet, mean)
ggplot(data = df, aes(x = pet, y = mean, fill = sex)) +
geom_bar(stat = 'identity',
position = position_dodge2(preserve = "single",
padding = 0.2), width = 1)
I am trying to create a 2-factor plot where I can increase the distance between categories (dog vs. cat) WITHOUT affecting the padding between bars or width of the bars. This has been a whack-a-mole game -- I only seem to be able to change this distance by decreasing the width of the bar or padding, which I don't want to do. Any help is much appreciated. Reprex below...
sex <- c('f','m','f','m')
pet <- c('cat', 'cat', 'dog', 'dog')
mean <- c(4, 5, 4, 5)
df <- data.frame(sex, pet, mean)
ggplot(data = df, aes(x = pet, y = mean, fill = sex)) +
geom_bar(stat = 'identity',
position = position_dodge2(preserve = "single",
padding = 0.2), width = 1)
Share
Improve this question
edited Mar 16 at 16:48
stefan
127k6 gold badges38 silver badges76 bronze badges
Recognized by R Language Collective
asked Mar 16 at 15:44
wythe4wythe4
1391 silver badge9 bronze badges
1 Answer
Reset to default 1One option would be to use ggh4x
package which via scale_x_manual
allows to manually set the positions for the categories, i.e. whereas the ggplot2
will by default position the catgeories at 1, 2, ... we can shift the first category slightly to the left and the second slightly to the right, thereby increasing the space between categories:
library(ggplot2)
library(ggh4x)
ggplot(data = df, aes(x = pet, y = mean, fill = sex)) +
geom_bar(
stat = "identity",
position = position_dodge2(
preserve = "single",
padding = 0.2
), width = 1
) +
ggh4x::scale_x_manual(
values = c(.9, 2.1),
c_limits = c(.9, 2.1)
)