Setting Foot on Matplotlib: Basics of Plotting Categorical Data

Welcome to another exciting session! Today, we're stepping into the world of data visualization by introducing Matplotlib's visualization tools. We'll be learning the basics of plotting categorical data from our dataset and understanding the insight such visualization can provide.

Data visualization is an essential tool in data analysis—you can communicate complex data structures and uncover relationships, trends, and patterns in the data. It plays a pivotal role in exploratory data analysis, a fundamental skill for all data scientists.

Taking the passengers aboard Titanic as an example, each passenger belonged to a specific gender and a unique passenger class. Can we observe any underlying pattern that might be of interest? Are survival rates higher for a certain gender or passenger class? Or does the embarkation point play a role? We'll address these questions as we traverse the path of data visualization.

Introduction to Matplotlib

Matplotlib is an extensive library for creating static, animated, and interactive visualizations in Python. To make it versatile across multiple platforms, it offers a MATLAB-like interface.

Let's start by importing the pyplot module of the Matplotlib library:

import matplotlib.pyplot as plt

pyplot provides a high-level interface for creating attractive graphs. To demonstrate this, we'll first analyze the sex column of the Titanic dataset.

We retrieve the counts of each category — male and female — with value_counts(), and plotting them is as simple as calling plot() with the argument 'bar':

import matplotlib.pyplot as plt
import seaborn as sns

# Load the dataset
titanic_df = sns.load_dataset('titanic')

# Count total males and females
gender_data = titanic_df['sex'].value_counts()

# Create a bar chart
gender_data.plot(kind ='bar', title='Sex Distribution')
plt.show()

image

Enhancing Plots: Labels and Title

It's good practice to include a title and labels for the axes to make your plot more understandable. You can achieve this using xlabel(), ylabel(), and title() functions. Let's enhance our plot:

gender_data = titanic_df['sex'].value_counts()

gender_data.plot(kind ='bar')
plt.xlabel("Sex")
plt.ylabel("Count")
plt.title("Sex Distribution")
plt.show()

image

In this code, plt.xlabel("Sex") adds 'Sex' as the label for the x-axis, plt.ylabel("Count") adds 'Count' as the label for the y-axis, and plt.title("Sex Distribution") sets 'Sex Distribution' as the title for the plot.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal