John Stud - 1 year ago 78

R Question

I am a relative R / ggplot2 beginner and I looking to create the following plot below so that the y axis is calculated independently for each facet. For instance, I would like Time Period 1 percentages on the y axis to just be calculated by the data faceted by time period1, and the Time Period 2 percentages to be calculated by the data faceted by time period 2.

Currently, it is calculating them all together.

Here is my 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))

Answer Source

I would do something like this. Starting with your 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 for any reason you want different scales on the axis put the parameter scales = "free_y" inside faced_grid but the remove the coor_cartesian part. Hope this helps.