R ggplot2 geom_col条未与x轴对齐

t9eec4r0  于 2023-04-03  发布在  其他
关注(0)|答案(2)|浏览(129)

我想有一个条形图与不同的差距酒吧在同一组,这里举例说明代码。

df <- data.frame(
  group = rep(c("A", "B", "C"), each = 3),
  category = rep(c("X", "Y", "Z"), 3),
  value = rnorm(9)
)
df$width = ifelse(df$category=="X",2,1)

ggplot(df, aes(x = group, y = value, fill = category)) +
  geom_col(width = df$width,position = position_dodge2(padding = c(0.5,0,0))) +
  scale_fill_manual(values = c("red", "green", "blue"))

我得到差距的事情做,但酒吧是不是与x轴对齐,如图所示。

如何解决这个问题?谢谢。

jdgnovmf

jdgnovmf1#

问题可能是你的df$width变量。尝试设置它们,使每个类别的总和为1:

set.seed(1) # Make the result reproducible

df <- data.frame(
  group = rep(c("A", "B", "C"), each = 3),
  category = rep(c("X", "Y", "Z"), 3),
  value = rnorm(9)
)

df$width = ifelse(df$category=="X",.5,.25) # This is what I changed

ggplot(df, aes(x = group, y = value, fill = category)) +
  geom_col(width = df$width,
           position = position_dodge2(padding = c(0.5,0.5,0.5))) + # Also edited your padding variables
  scale_fill_manual(values = c("red", "green", "blue"))

结果:

km0tfn4u

km0tfn4u2#

position_dodge2()函数中使用preserve参数,这是您想要的吗?

ggplot(df, aes(x = group, y = value, fill = factor(category))) +
  geom_col(width = df$width,position = position_dodge2(padding = c(0.5,0,0),
                                                       preserve = 'single')) +
  scale_fill_manual(values = c("red", "green", "blue"))

根据OP的注解更新,尝试删除宽度参数。

ggplot(df, aes(x = group, y = value, fill = factor(category))) +
  geom_col(position = position_dodge2(padding = c(0.5,0,0),
                                                       preserve = 'single')) +
  scale_fill_manual(values = c("red", "green", "blue"))

相关问题