ggplot2 - 分面和单独的 y 轴计算

ggplot2 - facet and separate y axis calculations

我是 R / ggplot2 的相对初学者,我希望在下面创建以下绘图,以便为每个方面独立计算 y 轴。例如,我希望 y 轴上的时间段 1 百分比仅由时间段 1 分面的数据计算,时间段 2 百分比由时间段 2 分面的数据计算。

目前正在一起计算。

这是我当前的代码:

library(ggplot2)

### create data - Time Period 1

weapons <- rep(1, length = 31)
weapons <- c(weapons, rep(2, length = 9))
weapons <- c(weapons, rep(3, length = 6))
weapons <- c(weapons, rep(4, length = 0))
weapons <- c(weapons, rep(5, length = 5))
weapons <- c(weapons, rep(6, length = 0))
weapons <- c(weapons, rep(7, length = 29))

time <- rep(1, length = 80)

### create data - Time Period 2

weapons <- c(weapons, rep(1, length = 13))
weapons <- c(weapons, rep(2, length = 0))
weapons <- c(weapons, rep(3, length = 1))
weapons <- c(weapons, rep(4, length = 0))
weapons <- c(weapons, rep(5, length = 3))
weapons <- c(weapons, rep(6, length = 0))
weapons <- c(weapons, rep(7, length = 7))

time <- c(time, rep(2, length = 24))


weapons <- factor(weapons, levels = 1:7, labels = c("Small Arms", "Heavy Machine Guns", "Mortars", "Recoilless Rifles", "107mm+ Rockets, Missiles", "MANPADs", "Unspecified"))

time <- factor(time, levels = 1:2, labels = c("Time Period 1", "Time Period 2"))

d <- data.frame(weapons, time)

ggplot(d, aes(x=weapons, y=(..count..) /sum (..count..), fill = (weapons))) + geom_bar() + geom_text(stat='count', aes(label=..count..), vjust = -1) + facet_grid(time ~ .) + coord_cartesian(ylim = c(0, .6))

我会做这样的事情。从您的 d 数据框开始:

dSummarised <- group_by(d, time, weapons) %>% 
    summarise(n = n()) %>% 
    mutate(percent = n / sum(n))
ggplot(dSummarised, aes(x=weapons, y=percent, fill = (weapons))) + 
    geom_bar(stat = "identity") + 
    geom_text(aes(label=n), vjust = -1) + 
    facet_grid(time ~ .) + 
    coord_cartesian(ylim = c(0, .6))

如果出于任何原因你想在轴上使用不同的刻度,请将参数 scales = "free_y" 放在 faced_grid 中,但删除 coor_cartesian 部分。 希望这有帮助。

尽可能多地保留现有代码,将对 facet_grid 的调用替换为:

 facet_wrap(~time, scales = 'free_x', nrow = 2)