geom_bar(position =“dodge”)

时间:2016-06-29 13:45:34

标签: r ggplot2

我想用相同宽度的条画出情节。这是我的最小示例代码:

data <- data.frame(A = letters[1:17],
                   B = sample(1:500, 17),
                   C = c(rep(1, 5), rep(2, 6), rep(c(3,4,5), each = 2)))

ggplot(data,
       aes(x = C,  y = B, label = A,
           fill = A)) +
  geom_bar(stat = "identity", position = "dodge") +
  geom_text(position = position_dodge(width = 0.9), angle = 90)

结果如上图所示: enter image description here

条形的宽度取决于变量C中给出的组中的观察数。我想让每个酒吧都有相同的宽度。

facet_grid(~C)有效(条形宽度相同),这不是我的意思:

ggplot(data,
       aes(x = C,  y = B, label = A,
           fill = A)) +
  geom_bar(stat = "identity", position = "dodge") +
  geom_text(position = position_dodge(width = 0.9), angle = 90) +
  facet_grid(~C)

enter image description here

我想要的是在第一张照片中绘制情节,但条形宽度与列C中每个级别的观察次数无关。我该怎么办?

[编辑] geom_bar(width)更改了酒吧组的宽度,但第五组中的酒吧仍然比第一组更宽,所以这不是我问题的答案。

1 个答案:

答案 0 :(得分:22)

<强>更新

ggplot2_3.0.0版以来,您现在可以position_dodge2使用preserve = c("total", "single")

ggplot(data,aes(x = C,  y = B, label = A, fill = A)) +
  geom_col(position = position_dodge2(width = 0.9, preserve = "single")) +
  geom_text(position = position_dodge2(width = 0.9, preserve = "single"), angle = 90, vjust=0.25)

enter image description here

原始回答

如前所述,您可以像answer一样: 将AC转换为因子,并使用tidyr的{​​{1}}添加看不见的变量。自最近的complete版本起,建议在ggplot2的情况下使用geom_col代替geom_bar

stat = "identity"

enter image description here

或使用互动术语:

data %>% 
  as.tibble() %>% 
  mutate_at(c("A", "C"), as.factor) %>% 
  complete(A,C) %>% 
  ggplot(aes(x = C,  y = B, fill = A)) +
  geom_col(position = "dodge")

enter image description here

通过最终将交互转换为数字,您可以根据所需的输出设置x轴。通过分组(data %>% ggplot(aes(x = interaction(C, A), y = B, fill = A)) + geom_col(position = "dodge") ),您可以计算匹配的中断。围绕ggplot参数的group_by的奇特东西是直接使用管道内的变量{}Breaks

C

enter image description here

编辑:

另一种方法是使用facet。使用data %>% mutate(gr=as.numeric(interaction(C, A))) %>% group_by(C) %>% mutate(Breaks=mean(gr)) %>% {ggplot(data=.,aes(x = gr, y = B, fill = A, label = A)) + geom_col(position = "dodge") + geom_text(position = position_dodge(width = 0.9), angle = 90 ) + scale_x_continuous(breaks = unique(.$Breaks), labels = unique(.$C))} 允许设置与x标度长度成比例的宽度。

space = "free_x"

enter image description here

您还可以使用library(tidyverse) data %>% ggplot(aes(x = A, y = B, fill = A)) + geom_col(position = "dodge") + facet_grid(~C, scales = "free_x", space = "free_x") 在底部绘制构面标签,并删除x轴标签

switch

enter image description here

相关问题