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.
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.
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.
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.
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.