r - ggplot2 - facet and separate y axis calculations -


i relative r / ggplot2 beginner , looking create following plot below y axis calculated independently each facet. instance, time period 1 percentages on y axis calculated data faceted time period1, , time period 2 percentages calculated data faceted time period 2.

currently, calculating them together.

here current code:

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)) 

i this. starting d data frame:

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)) 

if reason want different scales on axis put parameter scales = "free_y" inside faced_grid remove coor_cartesian part. hope helps.


Comments