3. Visualisation - Tasks
In this section, we will practice data visualization using Python and the matplotlib and seaborn packages. Follow the steps below to create various types of plots.
Using the same script 2-data-wrangling-and-visualization.py from the previous section, continue with the following tasks:
If you have imported pandas and read in the crashes dataset, you can proceed to the next steps. You will need to import matplotlib.pyplot and seaborn as well.
- Box Plot:
- Create a box plot to visualise the distribution of ages for different casualty types in the
crashesdataset. - Use
sns.boxplot()to create the box plot. - Add appropriate labels and a title to your plot.
- Save the box plot to a file named
age_boxplot.pngusingplt.savefig(). - Display the plot with
plt.show().
- 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).
- Use
sns.countplot()orvalue_counts().plot(kind='bar'). - Add custom colours and transparency to the bars.
- Add appropriate labels and a title.
- Save the plot to a file named
casualty_barplot.png.
- Export Your Plots:
- Save the box plot as a PNG file named
age_boxplot.png. - Save the bar plot as a PNG file named
casualty_barplot.png. - Check the documentation for
plt.savefig()by typinghelp(plt.savefig)in the console.
- Save the box plot as a PNG file named
R version: If you prefer R, the same exercises are available in R. Continue using the 2-data-wrangling-and-visualization.R script, load ggplot2 (part of tidyverse), and use geom_boxplot(), geom_bar(), and ggsave() to complete the same tasks.
Reuse
Copyright
© 2025 Robin Lovelace & contributors