Plotting Categorical Data with Matplotlib

MatplotlibMatplotlibBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

Matplotlib is a popular data visualization library in Python. It provides a variety of customizable plots and graphs for data exploration and presentation. In this lab, we will learn how to plot categorical variables using Matplotlib.

VM Tips

After the VM startup is done, click the top left corner to switch to the Notebook tab to access Jupyter Notebook for practice.

Sometimes, you may need to wait a few seconds for Jupyter Notebook to finish loading. The validation of operations cannot be automated because of limitations in Jupyter Notebook.

If you face issues during learning, feel free to ask Labby. Provide feedback after the session, and we will promptly resolve the problem for you.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/FileHandlingGroup(["`File Handling`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/BasicConceptsGroup(["`Basic Concepts`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/PlottingDataGroup(["`Plotting Data`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/PlotCustomizationGroup(["`Plot Customization`"]) python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/ModulesandPackagesGroup(["`Modules and Packages`"]) python(("`Python`")) -.-> python/PythonStandardLibraryGroup(["`Python Standard Library`"]) python(("`Python`")) -.-> python/DataScienceandMachineLearningGroup(["`Data Science and Machine Learning`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python/FileHandlingGroup -.-> python/with_statement("`Using with Statement`") matplotlib/BasicConceptsGroup -.-> matplotlib/importing_matplotlib("`Importing Matplotlib`") matplotlib/BasicConceptsGroup -.-> matplotlib/figures_axes("`Understanding Figures and Axes`") matplotlib/PlottingDataGroup -.-> matplotlib/line_plots("`Line Plots`") matplotlib/PlottingDataGroup -.-> matplotlib/scatter_plots("`Scatter Plots`") matplotlib/PlottingDataGroup -.-> matplotlib/bar_charts("`Bar Charts`") matplotlib/PlotCustomizationGroup -.-> matplotlib/titles_labels("`Adding Titles and Labels`") matplotlib/PlotCustomizationGroup -.-> matplotlib/legend_config("`Legend Configuration`") python/BasicConceptsGroup -.-> python/variables_data_types("`Variables and Data Types`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/DataStructuresGroup -.-> python/dictionaries("`Dictionaries`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/ModulesandPackagesGroup -.-> python/standard_libraries("`Common Standard Libraries`") python/PythonStandardLibraryGroup -.-> python/math_random("`Math and Random`") python/PythonStandardLibraryGroup -.-> python/data_collections("`Data Collections`") python/DataScienceandMachineLearningGroup -.-> python/numerical_computing("`Numerical Computing`") python/DataScienceandMachineLearningGroup -.-> python/data_visualization("`Data Visualization`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/with_statement -.-> lab-48598{{"`Plotting Categorical Data with Matplotlib`"}} matplotlib/importing_matplotlib -.-> lab-48598{{"`Plotting Categorical Data with Matplotlib`"}} matplotlib/figures_axes -.-> lab-48598{{"`Plotting Categorical Data with Matplotlib`"}} matplotlib/line_plots -.-> lab-48598{{"`Plotting Categorical Data with Matplotlib`"}} matplotlib/scatter_plots -.-> lab-48598{{"`Plotting Categorical Data with Matplotlib`"}} matplotlib/bar_charts -.-> lab-48598{{"`Plotting Categorical Data with Matplotlib`"}} matplotlib/titles_labels -.-> lab-48598{{"`Plotting Categorical Data with Matplotlib`"}} matplotlib/legend_config -.-> lab-48598{{"`Plotting Categorical Data with Matplotlib`"}} python/variables_data_types -.-> lab-48598{{"`Plotting Categorical Data with Matplotlib`"}} python/lists -.-> lab-48598{{"`Plotting Categorical Data with Matplotlib`"}} python/tuples -.-> lab-48598{{"`Plotting Categorical Data with Matplotlib`"}} python/dictionaries -.-> lab-48598{{"`Plotting Categorical Data with Matplotlib`"}} python/importing_modules -.-> lab-48598{{"`Plotting Categorical Data with Matplotlib`"}} python/standard_libraries -.-> lab-48598{{"`Plotting Categorical Data with Matplotlib`"}} python/math_random -.-> lab-48598{{"`Plotting Categorical Data with Matplotlib`"}} python/data_collections -.-> lab-48598{{"`Plotting Categorical Data with Matplotlib`"}} python/numerical_computing -.-> lab-48598{{"`Plotting Categorical Data with Matplotlib`"}} python/data_visualization -.-> lab-48598{{"`Plotting Categorical Data with Matplotlib`"}} python/build_in_functions -.-> lab-48598{{"`Plotting Categorical Data with Matplotlib`"}} end

Import Matplotlib

The first step is to import the Matplotlib library. We will also use the numpy library to generate some sample data.

import matplotlib.pyplot as plt
import numpy as np

Prepare Data

Next, we will prepare some sample data to plot. We will create a dictionary with the counts of different fruits, and then extract the keys and values into separate lists.

data = {'apple': 10, 'orange': 15, 'lemon': 5, 'lime': 20}
names = list(data.keys())
values = list(data.values())

Bar Plot

A bar plot is a good way to display categorical data. We can create a bar plot using the bar function.

plt.bar(names, values)
plt.title('Fruit Counts')
plt.xlabel('Fruit')
plt.ylabel('Count')
plt.show()

Scatter Plot

We can also create a scatter plot to show the relationship between two categorical variables. In this case, we will use the same fruit data and add some random noise to the counts to create a second variable.

noise = np.random.rand(len(values)) * 5
plt.scatter(names, values + noise)
plt.title('Fruit Counts with Noise')
plt.xlabel('Fruit')
plt.ylabel('Count')
plt.show()

Line Plot

A line plot can be used to show how a categorical variable changes over time. In this example, we will use data about the happiness levels of cats and dogs during different activities.

cat = ["bored", "happy", "bored", "bored", "happy", "bored"]
dog = ["happy", "happy", "happy", "happy", "bored", "bored"]
activity = ["combing", "drinking", "feeding", "napping", "playing", "washing"]
plt.plot(activity, dog, label="dog")
plt.plot(activity, cat, label="cat")
plt.title('Happiness Levels')
plt.xlabel('Activity')
plt.ylabel('Happiness')
plt.legend()
plt.show()

Summary

In this lab, we learned how to plot categorical variables using Matplotlib. We created bar plots, scatter plots, and line plots to visualize different types of categorical data. By customizing the axes labels, titles, and legends, we can create informative and visually appealing plots to communicate our data effectively.

Other Matplotlib Tutorials you may like