【问题标题】:ggplot2 - facet and separate y axis calculationsggplot2 - 平面和单独的 y 轴计算
【发布时间】:2016-08-08 17:54:57
【问题描述】:

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

【问题讨论】:

    标签: r ggplot2 visualization


    【解决方案1】:

    我会做这样的事情。从您的 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" 放入 faces_grid 但删除 coor_cartesian 部分。 希望这会有所帮助。

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 谢谢,我试了一下,它做了一些我喜欢的改进,但它仍然没有计算独立于时间段 1 的时间段 2 的 y 轴百分比。
      • 哎呀,忽略了这一点。在这种情况下,@ValterBeakovic 的解决方案是我会做的。请注意,它需要 dplyr 包。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-01
      • 2023-03-26
      • 1970-01-01
      相关资源
      最近更新 更多