Hamburger Icon
  • Labs icon Lab
  • Data
Labs

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.

Labs

Path Info

Level
Clock icon Beginner
Duration
Clock icon 53m
Published
Clock icon Dec 06, 2023

Contact sales

By filling out this form and clicking submit, you acknowledge ourΒ privacy policy.

Table of Contents

  1. 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(), and plt.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. Set marker='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 with fig.subplots(), and finally use the ax.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(), and plt.ylabel() to add the text to the plot. To view the parameters that plt.title() accepts, use plt.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 of plt.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 of plt.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 of plt.plot() function to '#FFD700'.

    πŸ”‘ Solution
    import matplotlib.pyplot as plt
    
    # Create a plot with color '#FFD700'
    plt.plot([0, 1], [0, 1], color='#FFD700')
    
  2. 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 as pd and matplotlib.pyplot as plt.

    πŸ”‘ 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 variable df. The df.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. Pass age_spend_average.index as the x-axis and age_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(), and plt.ylabel() to add a title, x-label, and y-label respectively. Use plt.grid() to add a grid. To change the line style to dashed, pass '--' as an additional argument to plt.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)
    
  3. 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() and plt.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 use as 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 and df.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(), and plt.ylabel() to add title and labels. Use the c parameter in plt.scatter() and the provided code to set the color of each point in the scatter plot. Set alpha=0.5 in the plt.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')
    
  4. 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(), and plt.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 use as 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 and df.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 the df['Category'].value_counts().index and df['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(), and plt.ylabel() functions to add a title, x-label, and y-label respectively. Use plt.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 the df['Category'].value_counts().index and df['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.