07. Matplotlib
07. Matplotlib
in Python
What is Matplotlib?
History of Matplotlib
Matplotlib was inspired by MATLAB's plotting capabilities and has since become the backbone
of visualization in Python, with various high-level libraries like Seaborn built on top of it.
1. Open Command Prompt: Ensure you have administrative privileges to install Python
packages.
2. Set up User Account: Confirm that Python and pip are installed and added to the system
PATH.
3. Run the Installation Command:
import matplotlib
print(matplotlib.__version__)
Ensure that your system is connected to the internet while running the pip command.
Using Matplotlib
pg. 1
1. Importing Matplotlib:
o Import the core library:
import matplotlib
2. Check the Version: To confirm which version of Matplotlib is installed, use the
following:
import matplotlib as mt
print(mt.__version__)
• Pyplot Submodule: Most of the utility functions for creating visualizations lie in
matplotlib.pyplot, which simplifies plotting through concise function calls.
• Customization: Offers extensive control over every element of a figure, including colors,
markers, line styles, and labels.
• Integration: Seamlessly integrates with NumPy, pandas, and Jupyter Notebooks for
streamlined workflows.
• Types of Visualizations:
o Line charts
o Bar charts
o Histograms
o Scatter plots
o Pie charts
o Box plots
o Heatmaps, and more.
# Define data
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
# Create plot
plt.plot(x, y, label='Linear Growth', color='blue', marker='o')
pg. 2
# Add labels and title
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Basic Line Plot')
# Add legend
plt.legend()
1. Flexibility: Provides low-level control over visual elements for advanced customizations.
2. Wide Range of Plots: Supports nearly every type of data visualization.
3. Extensibility: Works well with high-level libraries like Seaborn for enhanced aesthetics.
4. Community Support: Extensive documentation and a vibrant community for
troubleshooting.
The plot() function in Matplotlib is a versatile tool for drawing points (markers) and lines on a
2D diagram. By default, it connects points with a line, making it suitable for creating line charts,
trends, or simple graphs.
Key Concepts:
1. Function Overview:
o plot(x, y): Plots a line or points connecting the x and y coordinates.
o Parameters:
▪ x: An array-like structure (list, tuple, or NumPy array) that contains the
values for the x-axis (horizontal).
▪ y: An array-like structure for the y-axis (vertical).
pg. 3
o If y is omitted, the function assumes values starting from 0 for the x-axis and
takes x as the y-values.
Plotting Points:
The plot() function can be used to draw specific points on a diagram. By default:
When a continuous line is needed to connect the points, the plot() function handles it by
default.
# Data points
x = [0, 6]
y = [0, 250]
pg. 4
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
Matplotlib allows you to customize the appearance of the line and markers:
# Define points
x = [0, 2, 4, 6]
y = [0, 50, 150, 250]
# Data points
x = [0, 2, 4, 6]
y = [0, 50, 150, 250]
pg. 5
# Add title and labels
plt.title("Line Plot with Grid")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
# Show plot
plt.show()
You can plot multiple lines on the same graph by calling plot() multiple times or passing
additional x, y pairs.
# Line 1 data
x1 = [0, 2, 4, 6]
y1 = [0, 50, 150, 250]
# Line 2 data
x2 = [0, 2, 4, 6]
y2 = [0, 30, 90, 180]
pg. 6
Hands-on Exercises:
1. Plot a line connecting (0,0), (3,100), and (6,200) with square markers and a dashed line.
2. Add a grid to the graph and customize its color and style.
3. Create a graph with two intersecting lines and add a legend to identify them.
To plot only markers without connecting them with lines, use the format string parameter 'o',
which represents circular markers.
Example:
import matplotlib.pyplot as plt
import numpy as np
x = np.array([0, 6])
y = np.array([0, 250])
plt.plot(x, y, 'o')
plt.show()
Explanation:
• plt.plot(x, y, 'o'): Plots the points (0, 0) and (6, 250) with circular markers.
Example:
import matplotlib.pyplot as plt
import numpy as np
x = np.array([1, 2, 6, 8])
y = np.array([3, 8, 1, 10])
plt.plot(x, y)
plt.show()
Explanation:
• This will connect the points (1, 3), (2, 8), (6, 1), and (8, 10) with a line.
pg. 7
Default X-Axis
If no x values are specified, Matplotlib automatically uses the indices of the y array as the x
values.
Example:
import matplotlib.pyplot as plt
import numpy as np
plt.plot(y)
plt.show()
Explanation:
Matplotlib Markers
Markers are used to emphasize points in a plot. You can specify markers using the marker
keyword argument.
Example:
import matplotlib.pyplot as plt
import numpy as np
y = np.array([3, 8, 1, 10])
plt.plot(y, marker='o')
plt.show()
Marker Description
'o' Circle
'*' Star
'.' Point
'x' X (thin)
pg. 8
'X' X (filled)
's' Square
'D' Diamond
The fmt parameter allows you to define the marker, line style, and color in a single string.
Syntax:
marker | line | color
Example:
import matplotlib.pyplot as plt
import numpy as np
y = np.array([3, 8, 1, 10])
plt.plot(y, 'o:r')
plt.show()
Explanation:
Line Styles
You can customize the appearance of lines using the following styles:
pg. 9
Color Options
'r' Red
'g' Green
'b' Blue
'c' Cyan
'm' Magenta
'y' Yellow
'k' Black
'w' White
Marker Size
Example:
import matplotlib.pyplot as plt
import numpy as np
y = np.array([3, 8, 1, 10])
Explanation:
pg. 10
Use xlabel() and ylabel() to label axes.
x = np.array([0, 1, 2, 3, 4, 5])
y = np.array([0, 8, 12, 20, 26, 38])
plt.plot(x, y)
plt.xlabel("Overs")
plt.ylabel("Runs")
plt.show()
Title:
plt.title("Sport Data")
Font Customization:
plt.xlabel("Overs", fontdict=font2)
plt.ylabel("Runs", fontdict=font2)
plt.title("Sport Data", fontdict=font1)
plt.show()
x1 = np.array([0, 1, 2, 3])
y1 = np.array([3, 8, 1, 10])
x2 = np.array([0, 1, 2, 3])
y2 = np.array([6, 2, 7, 11])
Marker Customization
• Keyword Argument: markerfacecolor (short form mfc) controls the color of the marker face.
• Example:
pg. 11
import matplotlib.pyplot as plt
import numpy as np
y = np.array([3, 8, 1, 10])
plt.plot(y, marker='o', ms=20, mfc='r')
plt.show()
Linestyle Argument
• Use the linestyle (or ls) argument to change the line style.
• Available Styles:
o '-' (solid)
o '--' (dashed)
o '-.' (dashdot)
o ':' (dotted)
• Example:
plt.plot(y, linestyle='dotted')
Line Customization
Line Color
plt.plot(y, color='pink')
Line Width
plt.plot(y, linewidth=5)
plt.xlabel("X-axis label")
plt.ylabel("Y-axis label")
Adding a Title
pg. 12
plt.title("Plot Title")
• The loc argument in title() positions the title (left, right, center).
Font Customization
• Use fontdict in xlabel(), ylabel(), and title() to set font properties like size, color,
and family.
Grid Lines
plt.grid()
Multiple Plots
Subplots
plt.subplot(1, 2, 1)
plt.plot(x, y)
plt.subplot(1, 2, 2)
plt.plot(x, z)
Super Title
plt.suptitle("Overall Title")
Scatter Plots
pg. 13
• Basic Example:
plt.scatter(x, y)
plt.scatter(x, y, color='red')
You can customize font properties for plot titles and axis labels using the fontdict parameter in
xlabel(), ylabel(), and title().
Example Code:
x = np.array([0, 1, 2, 3, 4, 5])
y = np.array([0, 8, 12, 20, 26, 38])
plt.plot(x, y)
plt.xlabel('Overs', fontdict=font2)
plt.ylabel('Runs', fontdict=font2)
plt.title('Sport Data', fontdict=font1)
plt.show()
Output:
The title and labels will be styled as specified by font1 and font2.
The title's position can be adjusted using the loc parameter in the title() method. Legal values
are 'left', 'right', and 'center' (default).
Example Code:
pg. 14
plt.title('Sport Data', loc='left')
Grid lines enhance readability and can be added using the grid() function.
Example Code:
plt.grid()
Using subplot()
The subplot() function allows you to display multiple plots in a single figure.
Example Code:
# Plot 1
x1 = np.array([0, 1, 2, 3])
y1 = np.array([3, 8, 1, 10])
plt.subplot(2, 1, 1)
plt.plot(x1, y1)
# Plot 2
x2 = np.array([0, 1, 2, 3])
y2 = np.array([10, 20, 30, 40])
plt.subplot(2, 1, 2)
plt.plot(x2, y2)
plt.show()
plt.suptitle('My Data')
plt.scatter(x, y)
pg. 15
Customizing Colors and Sizes:
Example Code:
Adjusting Transparency:
plt.scatter(x, y, alpha=0.5)
Bar Plots
plt.barh(x, y)
plt.bar(x, y, width=0.5)
Histograms
Example Code:
Pie Charts
pg. 16
x = np.array([35, 25, 25, 15])
plt.pie(x)
Adding Labels:
plt.pie(x, startangle=90)
You can use the fontdict parameter in xlabel(), ylabel(), and title() to customize font
properties for the title and labels.
x = np.array([0, 1, 2, 3, 4, 5])
y = np.array([0, 8, 12, 20, 26, 38])
plt.plot(x, y)
plt.xlabel("Overs", fontdict=font2)
plt.ylabel("Runs", fontdict=font2)
plt.title("Sport Data", fontdict=font1)
plt.show()
The loc parameter in title() can position the title. Legal values: 'left', 'right', 'center'.
plt.grid()
pg. 17
The subplot() function allows multiple plots in one figure. It takes three arguments: rows,
columns, and index of the plot.
plt.subplot(1, 2, 1)
plt.plot(x, y)
plt.subplot(1, 2, 2)
plt.plot(x, y)
plt.show()
plt.subplot(2, 1, 1)
plt.plot(x, y)
plt.subplot(2, 1, 2)
plt.plot(x, y)
plt.show()
Scatter Plots
plt.scatter(x, y)
plt.show()
Bar Graphs
pg. 18
Vertical Bars
plt.bar(x, y)
plt.show()
Horizontal Bars
plt.barh(x, y)
plt.show()
plt.barh(x, y, width=0.5)
plt.show()
Histograms
Pie Charts
Adding Labels
Exploding a Wedge
explode = [0.2, 0, 0, 0]
plt.pie(x, labels=labels, explode=explode)
plt.show()
pg. 19
Adding Shadows
Adding a Legend
plt.legend(title="Four Fruits:")
plt.show()
pg. 20