- Lab
- Data

Getting Started with Matplotlib Hands-on Practice
Dive into the essentials of data visualization with this Matplotlib lab. Starting with the library's architecture, you'll learn to create and customize plots, including adding text and experimenting with color schemes. Progressing to real-world applications, you'll build line charts to analyze trends and scatter plots to examine variable relationships. Finally, you'll explore the dynamics of bar charts, both vertical and horizontal, gaining skills in enhancing data presentation. This lab offers a concise yet comprehensive hands-on experience with one of Python's key visualization tools.

Path Info
Table of Contents
-
Challenge
Exploring Matplotlibβs Architecture
Exploring Matplotlibβs Architecture
To review the concepts covered in this step, please refer to the Understanding Matplotlibβs Architecture module of the Getting Started with Matplotlib course.
Understanding Matplotlibβs architecture is important because it forms the foundation of how we create and customize plots. This step will focus on creating figures, adding text elements, and customizing colors.
Let's dive into the world of Matplotlib and explore its architecture. In this step, you'll create a figure using both the scripting and artist layers of Matplotlib. You'll also learn how to add text elements to your plot and customize colors using various methods such as basic color names, single letter color codes, and hexadecimal color codes. Tools you'll use include the
plt.figure()
,plt.plot()
, andplt.subplots()
functions.
Task 1.1: Creating a Plot using Scripting Layer
Create a plot using the scripting layer of Matplotlib. Use the
plt.plot()
function to accomplish this.π Hint
Use the
plt.plot()
function with two numbers as parameters. Setmarker='o'
to make the point appear.π Solution
import matplotlib.pyplot as plt # Create a plot using plt.plot() plt.plot(2, 2, marker='o')
Task 1.2: Creating a Plot using Artist Layer
Create a plot using the artist layer of Matplotlib. Create a figure with
plt.figure()
followed by the axis and plot.π Hint
Instantiate the figure with
plt.figure
, make the axis withfig.subplots()
, and finally use theax.plot()
method of the axis object to make the plot.π Solution
# Create a figure fig = plt.figure() ax = fig.subplots() ax.plot(2, 2, marker='o')
Task 1.3: Adding Text to a Plot
Add a title, xlabel and ylabel to a plot. Set the title's font size to 14 and color to red.
π Hint
Use the
plt.title()
,plt.xlabel()
, andplt.ylabel()
to add the text to the plot. To view the parameters thatplt.title()
accepts, useplt.title?
.π Solution
# Create a plot plt.plot([0, 1], [0, 1]) # Add text plt.xlabel('X-axis Label') plt.ylabel('Y-axis Label') plt.title('My Customized Title', fontsize=14, color='red')
Task 1.4: Customizing Colors using Basic Color Names
Customize the color of a plot using basic color names. Create a plot using
plt.plot()
and set the color to 'red'.π Hint
Set the
color
argument ofplt.plot()
function to'red'
.π Solution
import matplotlib.pyplot as plt # Create a plot with color 'red' plt.plot([0, 1], [0, 1], color='red')
Task 1.5: Customizing Colors using Single Letter Color Codes
Customize the color of a plot using single letter color codes. Create a plot using
plt.plot()
and set the color to 'g' (green).π Hint
Set the
color
argument ofplt.plot()
function to'g'
.π Solution
import matplotlib.pyplot as plt # Create a plot with color 'g' plt.plot([0, 1], [0, 1], color='g')
Task 1.6: Customizing Colors using Hexadecimal Color Codes
Customize the color of a plot using hexadecimal color codes. Create a plot using
plt.plot()
and set the color to '#FFD700' (gold).π Hint
Set the
color
argument ofplt.plot()
function to'#FFD700'
.π Solution
import matplotlib.pyplot as plt # Create a plot with color '#FFD700' plt.plot([0, 1], [0, 1], color='#FFD700')
-
Challenge
Building Line Charts
Building Line Charts
To review the concepts covered in this step, please refer to the Building Line Charts module of the Getting Started with Matplotlib course.
Building line charts is important because they provide a clear view of data trends over time. This step will focus on creating and customizing line charts using real-world data.
Now that you've got a grasp on Matplotlib's architecture, let's put that knowledge to use by creating some line charts. In this step, you'll use the
plt.plot()
function to create a simple line chart. You'll also learn how to group records by a specific column and count the number of occurrences. Additionally, you'll customize the appearance of your line chart using markers and line styles.
Task 2.1: Importing Necessary Libraries
Before we start with the actual task, we need to import the necessary libraries. Import pandas for data manipulation and matplotlib for data visualization.
π Hint
Use the
import
keyword to import pandas aspd
and matplotlib.pyplot asplt
.π Solution
import pandas as pd import matplotlib.pyplot as plt
Task 2.2: Loading the Dataset
Load the dataset
'Marketing_data.csv'
into a pandas DataFrame. Display the first few rows of the data.π Hint
Use the
pd.read_csv()
function to read the csv file. Assign the DataFrame to the variabledf
. Thedf.head()
method will display the first 5 rows.π Solution
df = pd.read_csv('Marketing_data.csv') df.head()
Task 2.3: Grouping and Getting Cost Info
Use the provided code to group the records by the 'Age' column and record the average cost, recorded in the 'Amount' column, for each age.
π Hint
The provided code assumes that you saved the data in a DataFrame named
df
.π Solution
age_spend_average = df.groupby('Age').Amount.mean()
Task 2.4: Creating a Line Chart
Create a line chart to visualize the average cost as age increases. Use 'Age' as the x-axis and 'Cost' as the y-axis.
π Hint
Use the
plt.plot()
function to create a line chart. Passage_spend_average.index
as the x-axis andage_spend_average.values
as the y-axis.π Solution
plt.plot(age_spend_average.index, age_spend_average.values)
Task 2.5: Customizing the Line Chart
Recreate your plot from
Task 2.4
and customize the line chart by adding a title, x-label, y-label, and grid. Also, change the line style to dashed.π Hint
Use
plt.title()
,plt.xlabel()
, andplt.ylabel()
to add a title, x-label, and y-label respectively. Useplt.grid()
to add a grid. To change the line style to dashed, pass'--'
as an additional argument toplt.plot()
.π Solution
plt.plot(age_spend_average.index, age_spend_average.values, '--') plt.title('Average Spend Amount per Age') plt.xlabel('Age') plt.ylabel('Average Spend ($)') plt.grid(True)
-
Challenge
Working with Scatter Plots
Working with Scatter Plots
To review the concepts covered in this step, please refer to the Working with Scatter Plots module of the Getting Started with Matplotlib course.
Scatter plots are important because they allow us to identify relationships between two variables. This step will focus on creating and customizing scatter plots.
In this step, you'll dive into the world of scatter plots. You'll learn how to create scatter plots using both the
plt.scatter()
andplt.plot()
functions. You'll also learn how to identify positive correlations between two variables and how to customize the appearance of your scatter plot, including coloring markers based on another column from the data frame.After the successful completion of each task, proceed to execute the Jupyter Notebook cell by using the
Ctrl/cmd + Enter
key combination to enact any necessary changes.
Task 3.1: Importing Necessary Libraries
Import the necessary libraries for data manipulation and visualization, pandas and matplotlib.
π Hint
Use the
import
keyword to import pandas and matplotlib.pyplot. Remember to useas
keyword to give them an alias.π Solution
import pandas as pd import matplotlib.pyplot as plt
Task 3.2: Loading the Dataset
Load the dataset 'Marketing_data.csv' into a pandas DataFrame. Display the first few rows.
π Hint
Use the
pd.read_csv()
function to load the dataset anddf.head()
to print the first 5 rows.π Solution
df = pd.read_csv('Marketing_data.csv') df.head()
Task 3.3: Creating a Basic Scatter Plot
Create a scatter plot using
plt.scatter()
function to visualize the relationship between 'Age' and 'Amount'.π Hint
Use
plt.scatter()
function with the 'Age' data and 'Amount' data as arguments.π Solution
plt.scatter(df['Age'], df['Amount'])
Task 3.4: Customizing the Scatter Plot
Customize the scatter plot by adding a title, x-label, and y-label. Also, color the markers based on 'Gender'. Finally, make the points partially transparent with the
alpha
parameter.π Hint
Use
plt.title()
,plt.xlabel()
, andplt.ylabel()
to add title and labels. Use thec
parameter inplt.scatter()
and the provided code to set the color of each point in the scatter plot. Setalpha=0.5
in theplt.scatter()
function to make the points partially transparent.π Solution
# provided code colors = ['blue' if gender=='Male' else 'pink' for gender in df['Gender']] # scatter plot plt.scatter(df['Age'], df['Amount'], c=colors) plt.title('Age vs Amount') plt.xlabel('Age') plt.ylabel('Amount')
Task 3.5: Creating a Scatter Plot using plt.plot()
Create a basic scatter plot using
plt.plot()
function to visualize the relationship between 'Age' and 'Amount'.π Hint
Use
plt.plot()
function with 'Age' data and 'Amount' data as arguments and 'o' as the marker. Set the line style to be 'None' to remove the lines.π Solution
plt.plot(df['Age'], df['Amount'], marker='o', linestyle='None')
-
Challenge
Creating Bar Charts
Creating Bar Charts
To review the concepts covered in this step, please refer to the Creating Bar Charts module of the Getting Started with Matplotlib course.
Bar charts are important because they allow us to compare and rank categories. This step will focus on creating and customizing bar charts in interactive mode.
In this final step, you'll learn how to create various types of bar charts including vertical and stacked bar charts. You'll also learn how to customize bar chart properties such as bar color, width, opacity, and alignment. You'll learn to set up interactive mode and how to add labels and data labels to your bar chart. Tools you'll use include the
plt.bar()
,plt.barh()
, andplt.xticks()
functions.
Task 4.1: Importing Necessary Libraries
Import the necessary libraries for data manipulation and visualization, pandas and matplotlib.
π Hint
Use the
import
keyword to import pandas and matplotlib.pyplot. Remember to useas
keyword to give them an alias.π Solution
import pandas as pd import matplotlib.pyplot as plt
Task 4.2: Loading the Dataset
Load the dataset 'Marketing_data.csv' into a pandas DataFrame. Display the first few rows.
π Hint
Use the
pd.read_csv()
function to load the dataset anddf.head()
to print the first 5 rows.π Solution
df = pd.read_csv('Marketing_data.csv') df.head()
Task 4.3: Setting Up Interactive Plots
Use
%matplotlib notebook
to change matplotlib to interactive mode.π Hint
The interactive mode will allow you to create plots and modify them with difference cells. To create new plots, the interactive session must be closed.
π Solution
%matplotlib notebook
Task 4.4: Creating a Basic Bar Chart
Create a basic bar chart to visualize the count of each product category in the 'Category' column. Use the
df.value_counts()
method to get the counts. The x-ticks will overlap -- we'll address this in the next task.Use the provided code to set an effective figure size.
π Hint
Use the
plt.bar()
function to create a bar chart. Use thedf['Category'].value_counts().index
anddf['Category'].value_counts().values
as the x and y values respectively.π Solution
plt.figure(figsize=(4,4)) plt.bar(df['Category'].value_counts().index, df['Category'].value_counts().values)
Task 4.5: Customizing the Bar Chart
Customize the bar chart by adding a title, x-label, and y-label. Rotate the x-ticks to be more readable with
plt.xticks(rotation=30, ha='right')
.π Hint
Use the
plt.title()
,plt.xlabel()
, andplt.ylabel()
functions to add a title, x-label, and y-label respectively. Useplt.xticks(rotation=30, ha='right')
to rotate the x-ticks so that they are more readable.π Solution
plt.title('Product Category Counts') plt.xlabel('Category') plt.ylabel('Count') plt.xticks(rotation=30, ha='right')
Task 4.6: Creating a Horizontal Bar Chart
Stop the previous interactive chat session and create a new plot. Make a horizontal bar chart to visualize the count of each product category.
Use the provided code to set an appropriate figure size.
π Hint
Use the
plt.barh()
function to create a horizontal bar chart. Use thedf['Category'].value_counts().index
anddf['Category'].value_counts().values
as the y and x values respectively.π Solution
plt.figure(figsize=(4,4)) plt.barh(df['Category'].value_counts().index, df['Category'].value_counts().values)
What's a lab?
Hands-on Labs are real environments created by industry experts to help you learn. These environments help you gain knowledge and experience, practice without compromising your system, test without risk, destroy without fear, and let you learn from your mistakes. Hands-on Labs: practice your skills before delivering in the real world.
Provided environment for hands-on practice
We will provide the credentials and environment necessary for you to practice right within your browser.
Guided walkthrough
Follow along with the authorβs guided walkthrough and build something new in your provided environment!
Did you know?
On average, you retain 75% more of your learning if you get time for practice.