Skip to main content
Practice

Visualizing Data with Matplotlib

When analyzing data, visualizing numerical information with graphs can make it much easier to understand.

Matplotlib is a core library in Python for visualizing data as graphs.

In this lesson, we will learn the basic usage of Matplotlib and how to create line and bar graphs.


Installing Matplotlib​

You can install Matplotlib with the following command. Note that you might not need to install it separately if you're using an environment where it’s already installed.

Installing Matplotlib
pip install matplotlib

1. Basic Usage of Matplotlib​

The following code will display a line graph with x-values on the horizontal axis and y-values on the vertical axis.

Plotting a Basic Line Graph
import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [10, 20, 25, 30, 40]

plt.plot(x, y)
plt.title("Basic Line Graph")
plt.xlabel("X-Axis")
plt.ylabel("Y-Axis")

plt.show()

plt.plot(x, y) is a function that creates a line graph using x-axis and y-axis data.

plt.title(), plt.xlabel(), and plt.ylabel() set the graph title and axis labels.

plt.show() displays the graph.


2. Customizing Graph Style​

In Matplotlib, you can adjust the color, line style, marker, and more for your graph.

Styled Line Graph
import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [10, 20, 25, 30, 40]

plt.plot(x, y, color='red', linestyle='--', marker='o')

plt.title("Styled Line Graph")
plt.xlabel("X-Axis")
plt.ylabel("Y-Axis")

plt.show()

πŸ“Œ Key Options​

  • color='red': Sets the line color to red.

  • linestyle='--': Applies a dashed line style.

  • marker='o': Adds circular (o) markers at data points.

These style options help make your graphs more readable and visually appealing.


3. Creating Bar Charts​

With Matplotlib, you can easily create bar charts for comparing data across categories.

Drawing a Bar Chart
import matplotlib.pyplot as plt

labels = ["A", "B", "C", "D"]
values = [30, 70, 50, 90]

plt.bar(labels, values, color=['red', 'blue', 'green', 'orange'])

plt.title("Basic Bar Chart")
plt.xlabel("Category")
plt.ylabel("Values")

plt.show()

plt.bar(x, y) is used for drawing bar charts with categories and values.

color=['red', 'blue', 'green', 'orange'] individually sets the color for each bar.

Bar charts are useful for comparing data across categories.


In the next lesson, we will cover histograms, scatter plots, pie charts, and subplots.

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.