ggplot2 - facet和单独的y轴计算

时间:2016-08-08 17:54:57

标签: r ggplot2 visualization

我是一名相对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))

2 个答案:

答案 0 :(得分:0)

我会做这样的事情。从您的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))

如果由于任何原因你想在轴上使用不同的刻度,则将参数scale =&#34; free_y&#34;在facing_grid里面但删除了coor_cartesian部分。 希望这会有所帮助。

答案 1 :(得分:0)

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

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