Matplotlib is a popular Python library used to create charts, graphs and other visualizations. It is widely used in data analysis, scientific computing and data science.
Matplotlib is a Python visualization library that provides tools for creating static, animated and interactive visualizations.
It is commonly used together with libraries such as NumPy and Pandas.
Matplotlib can be installed using pip.
pip install matplotlib
You can also use:
python -m pip install matplotlib
The pyplot module is commonly imported using the alias
plt.
import matplotlib.pyplot as plt
The plot() function can be used to create a line chart.
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [10, 20, 15, 30, 25]
plt.plot(x, y)
plt.show()
The show() function displays the chart.
The title() function adds a title to the chart.
import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [10, 20, 15, 25]
plt.plot(x, y)
plt.title("Student Performance")
plt.show()
Use xlabel() and ylabel() to label the axes.
import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [10, 20, 15, 25]
plt.plot(x, y)
plt.xlabel("Month")
plt.ylabel("Sales")
plt.title("Monthly Sales")
plt.show()
The grid() function displays grid lines on the chart.
import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [10, 20, 15, 25]
plt.plot(x, y)
plt.grid()
plt.show()
The linestyle argument can be used to change the line style.
plt.plot(
x,
y,
linestyle="--"
)
plt.show()
Common styles include:
- Solid line-- Dashed line: Dotted line-. Dash-dot lineMarkers can be used to highlight individual data points.
plt.plot(
x,
y,
marker="o"
)
plt.show()
Common marker examples include o, s, ^
and *.
import matplotlib.pyplot as plt
months = [
"Jan",
"Feb",
"Mar",
"Apr"
]
sales = [
100,
150,
120,
180
]
plt.plot(
months,
sales,
marker="o"
)
plt.title("Monthly Sales")
plt.xlabel("Month")
plt.ylabel("Sales")
plt.grid()
plt.show()
Multiple datasets can be plotted on the same axes.
import matplotlib.pyplot as plt
months = [1, 2, 3, 4]
python_students = [20, 30, 35, 40]
java_students = [15, 25, 30, 35]
plt.plot(
months,
python_students,
label="Python"
)
plt.plot(
months,
java_students,
label="Java"
)
plt.legend()
plt.show()
The legend() function displays labels for plotted datasets.
plt.plot(
[1, 2, 3],
[10, 20, 30],
label="Sales"
)
plt.legend()
plt.show()
The bar() function creates a vertical bar chart.
import matplotlib.pyplot as plt
courses = [
"Python",
"Java",
"SQL"
]
students = [
50,
40,
30
]
plt.bar(
courses,
students
)
plt.title("Students by Course")
plt.xlabel("Course")
plt.ylabel("Students")
plt.show()
The barh() function creates a horizontal bar chart.
courses = [
"Python",
"Java",
"SQL"
]
students = [
50,
40,
30
]
plt.barh(
courses,
students
)
plt.show()
The scatter() function creates a scatter plot.
import matplotlib.pyplot as plt
hours = [
1, 2, 3, 4, 5
]
marks = [
40, 50, 60, 75, 85
]
plt.scatter(
hours,
marks
)
plt.xlabel("Study Hours")
plt.ylabel("Marks")
plt.title("Study Hours vs Marks")
plt.show()
The pie() function creates a pie chart.
import matplotlib.pyplot as plt
courses = [
"Python",
"Java",
"SQL"
]
students = [
50,
30,
20
]
plt.pie(
students,
labels=courses,
autopct="%1.1f%%"
)
plt.title("Course Distribution")
plt.show()
A histogram shows the distribution of numerical data.
import matplotlib.pyplot as plt
marks = [
45, 50, 55, 60,
62, 65, 70, 72,
75, 80, 85, 90
]
plt.hist(marks)
plt.xlabel("Marks")
plt.ylabel("Frequency")
plt.title("Marks Distribution")
plt.show()
Subplots allow multiple charts to be placed within one figure.
import matplotlib.pyplot as plt
plt.subplot(1, 2, 1)
plt.plot(
[1, 2, 3],
[10, 20, 30]
)
plt.title("Line Chart")
plt.subplot(1, 2, 2)
plt.bar(
[1, 2, 3],
[30, 20, 10]
)
plt.title("Bar Chart")
plt.show()
Here, 1, 2, 1 means one row, two columns and the first plot.
For more structured visualizations, Matplotlib provides the
subplots() function.
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot(
[1, 2, 3],
[10, 20, 30]
)
ax.set_title("Sales")
ax.set_xlabel("Month")
ax.set_ylabel("Amount")
plt.show()
The figsize argument controls the figure dimensions.
import matplotlib.pyplot as plt
plt.figure(
figsize=(8, 5)
)
plt.plot(
[1, 2, 3],
[10, 20, 30]
)
plt.show()
The savefig() function saves a figure to a file.
import matplotlib.pyplot as plt
plt.plot(
[1, 2, 3],
[10, 20, 30]
)
plt.title("Sales")
plt.savefig(
"sales.png"
)
plt.show()
The file format can be inferred from the filename extension.
Matplotlib works well with NumPy arrays.
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(
0,
10,
0.1
)
y = np.sin(x)
plt.plot(x, y)
plt.title("Sine Wave")
plt.show()
Pandas DataFrames and Series can also be plotted using their plotting methods, which commonly use Matplotlib as the visualization backend.
import pandas as pd
import matplotlib.pyplot as plt
data = {
"Month": [
"Jan",
"Feb",
"Mar"
],
"Sales": [
100,
150,
130
]
}
df = pd.DataFrame(data)
df.plot(
x="Month",
y="Sales"
)
plt.title("Monthly Sales")
plt.show()
Functions such as xticks() and yticks() can be
used to control tick positions and labels.
import matplotlib.pyplot as plt
months = [
"Jan",
"Feb",
"Mar",
"Apr"
]
sales = [
100,
150,
120,
180
]
plt.plot(
months,
sales
)
plt.xticks(
rotation=45
)
plt.show()
The text() function can add text at a specified position.
import matplotlib.pyplot as plt
x = [1, 2, 3]
y = [10, 20, 30]
plt.plot(x, y)
plt.text(
2,
20,
"Important Point"
)
plt.show()
A box plot is useful for displaying the distribution of numerical data and identifying potential outliers.
import matplotlib.pyplot as plt
marks = [
45, 50, 55, 60,
62, 65, 70, 72,
75, 80, 85, 90
]
plt.boxplot(marks)
plt.title("Marks Distribution")
plt.show()
The xlim() and ylim() functions can control the
visible range of the axes.
import matplotlib.pyplot as plt
plt.plot(
[1, 2, 3, 4],
[10, 20, 30, 40]
)
plt.xlim(1, 4)
plt.ylim(0, 50)
plt.show()
The tight_layout() function can automatically adjust spacing
between plot elements.
import matplotlib.pyplot as plt
plt.plot(
[1, 2, 3],
[10, 20, 30]
)
plt.title("Sales")
plt.xlabel("Month")
plt.ylabel("Amount")
plt.tight_layout()
plt.show()
pyplot.plt.show() when a display is needed.import matplotlib.pyplot as plt
months = [
"Jan",
"Feb",
"Mar",
"Apr",
"May"
]
sales = [
100,
150,
130,
180,
200
]
plt.figure(
figsize=(8, 5)
)
plt.plot(
months,
sales,
marker="o",
label="Sales"
)
plt.title("Monthly Sales")
plt.xlabel("Month")
plt.ylabel("Sales")
plt.grid()
plt.legend()
plt.tight_layout()
plt.show()
matplotlib.pyplot is commonly imported as plt.plot() creates line charts.bar() creates vertical bar charts.barh() creates horizontal bar charts.scatter() creates scatter plots.pie() creates pie charts.hist() creates histograms.boxplot() creates box plots.title() adds a chart title.xlabel() and ylabel() label the axes.legend() displays labels for plotted datasets.grid() displays grid lines.savefig() saves a chart to a file.subplots() creates figure and axes objects.Question: Which Matplotlib function is commonly used to create a line chart?