3. Visualisation - Tasks
In this section, we will practice data visualization using R and the ggplot2 package from the tidyverse. Follow the steps below to create various types of plots.
Using the same script 2-data-wrangling-and-visualization.R from the previous section, continue with the following tasks:
If you have loaded the tidyverse package and read in the crashes dataset, you can proceed to the next steps. ggplot2 is part of the tidyverse, so you don’t need to load it separately.
- Box Plot:
- Create a box plot to visualise the distribution of ages for different casualty types in the
crashesdataset. - Use
ggplot()to specify the dataset and aesthetics, andgeom_boxplot()to create the box plot. - Add appropriate labels and a title to your plot.
- Save the box plot to an object named
age_boxplot. - Display the plot by calling the object name.
- Create a box plot to visualise the distribution of ages for different casualty types in the
- Bar Plot (Optional):
- Create a bar plot showing the count of casualties by type (pedestrian, cyclist, cat).
- Add custom colours and transparency to the bars.
- Add appropriate labels and a title.
- Save the plot to an object named
casualty_barplot.
- Export Your Plots:
- Save the box plot as a PNG file named
age_boxplot.pngusing theggsave()function. - Save the bar plot as a PNG file named
casualty_barplot.png. - Check the documentation for
ggsave()by typing?ggsavein the console.
- Save the box plot as a PNG file named
Reuse
Copyright
© 2025 Robin Lovelace & contributors