dog
和
cat
),而不影响条形宽度或组内的条之间的间距,则可以调整
scale_x_discrete()
任期代码:
library(ggplot2)
# Sample data
sex <- c('male', 'female', 'male', 'female')
pet <- c('cat', 'cat', 'dog', 'dog')
mean <- c(4, 5, 4, 5)
df <- data.frame(sex, pet, mean)
# Plot
ggplot(data = df, aes(x = pet, y = mean, fill = sex)) +
geom_bar(stat = 'identity',
position = position_dodge2(preserve = "single", padding = 0.2),
width = 0.8) + # Bar width stays the same
scale_x_discrete(expand = expansion(mult = c(0.5, 0.5))) + # Adds space between categories
theme_minimal()
发生了什么:
bar宽度:由width
geom_bar
0.8
调整。将其设置为padding
,以使组内的间距保持一致。
类别之间的空格:使用
position_dodge2
独立进行管理。 0.2
scale_x_discrete(expand = ...)
和mult
)之前和之后添加空间。这种方式,您可以分别控制类别和条形外观之间的间距,从而解决“ whack-a-a-mole”问题!