'Faceting the arrangement of the top 20 places visited by boys and girls
I encountered this problem while trying to arrange for total_number of boys and girls, but there was top places for boys that were not in the top 20 for girls. The visualization did not show an even representation of the sample because the top places of the girls are not the top places of the boys and vice versa (though they do visit similar places, just not in vast numbers).
| place | Category2 | total_number |
|---|---|---|
| Andorra la Vella | boy | 66394 |
| Yerevan | boy | 33539 |
| Vienna | boy | 29757 |
| Baku | girl | 24615 |
| Minsk | girl | 23847 |
| Brussels | girl | 23691 |
| Sarajevo | boy | 23285 |
| Sofia | boy | 21309 |
| Oslo | girl | 20982 |
| Zagreb | boy | 19885 |
I have arranged by the total_number descending, used head(20) and attempted to plot it. This did not look good because of empty spaces and out of order with respect to the boys and girls (category 2). I want to arrange for the top 20 of the data set, but I want the arrangement of total_number to alternate between girls and boys of Category2 to show an equal representation and no blanks in the top 20 of the visualization. How do I do this?
bg_places_top <- bg_places %>%
group_by(place, Category2) %>%
summarise(total_number = n()) %>%
arrange(desc(total_number) %>%
head(20) %>%
ggplot(aes(x = place, y = total_number)) +
geom_col(position = "dodge") +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) +
facet_wrap(~Category2))
Solution 1:[1]
If I understood you correctly one way to go about this is setting the scales argument inside the facet_wrap to "free" and order places according to the total_number (I used the - to invert increasing order):
library(ggplot2)
ggplot2::ggplot(bg_places, aes(x = reorder(place, -total_number), y = total_number)) +
ggplot2::geom_col() +
# use "free_x" if you want the all y-axis to have the same scale/height
ggplot2::facet_wrap(~Category2, scales = "free")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |

