Lecture

Visualizing Data with Matplotlib

When analyzing data, using graphs to visualize numerical data can make it much more intuitive 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

Running the code below 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.

Using these style settings, you can make your graphs more intuitive.


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.

Mission
0 / 1

Matplotlib is a library specialized for data visualization.

True
False

Lecture

AI Tutor

Design

Upload

Notes

Favorites

Help