问题描述 投票:0回答:1
dog

cat
),而不影响条形宽度或组内的条之间的间距,则可以调整
scale_x_discrete()
ggplot2 width padding geom-bar position-dodge
1个回答
0
投票

任期代码:

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
  1. 中使用

    0.8调整。将其设置为padding

    ,以使组内的间距保持一致。
    
    类别之间的空格:使用
    position_dodge2

    独立进行管理。
  2. 0.2
  3. 值在x轴上的类别(

    scale_x_discrete(expand = ...)mult

    )之前和之后添加空间。
    
    这种方式,您可以分别控制类别和条形外观之间的间距,从而解决“ whack-a-a-mole”问题!
    
        

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.