11.1 Exercise 5: barplot
- Import DataViz_source_files-main/files/population_age_group_per_sex_long_format.csv into an object called pop_age.
correction
- Create a barplot that shows the number of people per Year:
- Split by Sex (in the same plot: do not split into different plots):
correction
- Filter the data to keep only “Spain” in “Country”:
correction
- Show the bars next to each other.
correction
- Change default colors using scale_fill_manual() layer.
The structure is not easy to remember: take a peek at the answer!
correction
- Add a title, change the theme / background:
correction
8. Now split the plot by Age group using facet_wrap()
correction
- Save to a PDF file: Export -> Save as PDF. Note: when saving to PDF format, you cannot manualy drag the plot to get the size and proportion you want, but you can Preview before saving it.
If you prefer, you can save the file using ggsave() (or you can do both!).
correction
# first, save to an object
plot_age <- ggplot(data=pop_age_spain, mapping=aes(x=Year, y=Population, fill=Sex)) +
geom_bar(stat="identity", position="dodge") +
scale_fill_manual(values=c("darkgreen", "red")) +
ggtitle("Spanish population from 1950 to 2021 per sex") +
theme_minimal() +
facet_wrap(~Age_group)
# save file
ggsave(filename="population_age_sex_Spain.pdf", plot=plot_age, device = "pdf", units = "in", width = 10, height = 8)
- Save your filtered data as a .csv file: have a look at the write_csv() function from {readr}: