Mat Plot
Mat Plot
Matplotlib is a popular plotting library in Python. It was originally created by John D. Hunter in 2003
as a patch to IPython for enabling interactive MATLAB-style plotting via Gnuplot from the IPython
command line. Python was still in its early days, and Matplotlib was one of the first libraries to offer
robust capabilities for creating a wide range of static, animated, and interactive visualizations in
Python. It is particularly useful for those working in Python for data visualization and scientific
computing. Over the years, Matplotlib has evolved into a powerful library capable of producing
complex plots with fine-tuned details.
The library is designed to be understandable for beginners but powerful enough for experts.
Matplotlib allows for the creation of bar charts, scatter plots, histograms, error charts, power
spectra, and much more, with just a few lines of code.
To use Matplotlib, you first need to install it using pip if it's not already installed:
After installation, you import Matplotlib, typically its pyplot module, which provides a MATLAB-like
interface. The standard convention is to import it under the alias plt:
import numpy as np
Creating and Plotting a Linear Equation and a Quadratic
keyboard_arrow_down Equation with NumPy and Matplotlib
A linear equation in two variables (say, x and y) can be represented as y = mx + c, where m is the
slope of the line, and c is the y-intercept. Let's plot a simple linear equation using Matplotlib and
NumPy.
1. Create an array for x values: Use NumPy to create an array of x values from which y values will
be calculated.
2. Define the linear equation: Specify the slope (m) and intercept (c).
m = 2 # Slope
c = 3 # Intercept
y = m * x + c
np.linspace(start, stop, num) generates num evenly spaced samples, calculated over the
interval [start, stop].
plt.plot(x, y, label) plots y versus x as lines and/or markers with an optional label.
plt.title(), plt.xlabel(), and plt.ylabel() are used to add a title and labels to the axes.
plt.savefig() allows you to save the figure in various file formats such as PNG, JPEG, SVG,
PDF, and more.
This will produce a graph of the linear equation y = 2x + 3, showing a straight line that cuts through
the y-axis at 3 and has a slope of 2, rising two units in y for every increase of one unit in x.
A quadratic equation typically has the form y = ax^2 + bx + c, where a, b and c are constants.
# Generate x values
x = np.linspace(-1, 7, 400)
plt.legend()
# Add grid
plt.grid(True)
In this script:
x = np.linspace(-1, 7, 400) generates 400 points between -1 and 7. The range is chosen to
nicely show the shape of the curve, including the vertex of the parabola.
plt.title(), plt.xlabel(), and plt.ylabel() set the title and labels of the axes.
You can adjust the coefficients a, b, and c to explore different forms of quadratic curves.
keyboard_arrow_down Matplotlib Figure Object
In Matplotlib, the Figure object is a central concept. It acts as the container that holds everything
you see on the plot, as well as the space in which elements that make up the plot are drawn. Think
of the Figure object as a canvas on which various plots are drawn.
Key Characteristics:
Container: It holds all plot elements, such as axes, graphics, text, and labels.
Independence: You can create multiple figures. Each figure can contain multiple Axes.
Customizable: Its size, DPI (dots per inch), and other attributes can be adjusted according to
user needs.
When you create a figure in Matplotlib, you're setting up a space where plots will reside. Here’s how
you typically create a figure and add axes to it:
1. Figure and Axes Creation: A Figure object is created with a specified size using figsize=(8, 6).
An Axes object is then added to this figure. The list [0.1, 0.1, 0.85, 0.85] specifies the position
and dimensions of the axes within the figure.
2. Plotting Data: np.sin(x) computes the sine of each value in x, and these points are plotted as
a blue line.
3. Customization: The plot is customized with titles, labels, and a legend, which help in
understanding the plotted data.
When creating visualizations in Matplotlib, the figure serves as a canvas where multiple plots
(axes) can be arranged in various positions. Each set of axes can display different aspects or
components of data. For linear functions, these plots might represent different linear equations or
variations thereof.
Key Components:
Axes: The individual plots; each set of axes can contain its own elements like lines, labels,
ticks, and titles.
left, bottom: These determine the position of the bottom-left corner of the axes.
width, height: These determine the size of the axes.
This example demonstrates how to arrange six different axes within a single figure, each displaying
a simple linear function with a different slope and intercept, organized in various positions.
# Generate x values
x = np.linspace(0, 10, 100)
plt.show()
# Generate x values
x = np.linspace(0, 10, 100)
plt.show()
keyboard_arrow_down Matplotlib Subplots
Overview:
Matplotlib subplots allow you to create a grid of subplots within a single figure. This is very useful
when you need to display multiple plots in a structured layout to compare them side by side or in a
sequence.
plt.subplots() function: This is the key function to create a figure and a set of subplots. It
returns a tuple containing a Figure object and an array of Axes objects.
# Plot data
ax.plot([1, 2, 3, 4, 5], [1, 4, 9, 16, 25],label="y=x^2") # Plotting squares of the number
ax.legend()
Using plt.tight_layout() :
The plt.tight_layout() function is used to automatically adjust subplot parameters to give specified
padding and avoid overlap between subplots.
Example of plt.tight_layout():
# Create a 2x2 grid of subplots
fig, axs = plt.subplots(2, 2)
# Plot data
axs[0, 0].plot([1, 2, 3, 4, 5], [1, 4, 9, 16, 25])
axs[0, 1].plot([1, 2, 3, 4, 5], [1, 2, 3, 4, 5])
axs[1, 0].plot([1, 2, 3, 4, 5], [5, 4, 3, 2, 1])
axs[1, 1].plot([1, 2, 3, 4, 5], [25, 16, 9, 4, 1])
# Adjust layout
plt.tight_layout()
Experimenting with Subplot Parameters: You can adjust a multitude of parameters to customize
the appearance and functionality of subplots.
Common Parameters:
figsize: Tuple of width and height in inches to specify the size of the figure.
dpi: Dots per inch, resolution of the figure.
sharex, sharey: If set to True, subplots share the x or y axis.
subplot_kw: Dictionary of keywords passed to the add_subplot() call used to create each
subplot.
# Create a grid of subplots with shared y-axis and custom size
fig, axs = plt.subplots(2, 2, figsize=(10, 8), dpi=100, sharey=True, subplot_kw={'facecolor
# Plotting
axs[0, 0].plot([1, 2, 3, 4, 5], [1, 4, 9, 16, 25])
axs[0, 1].plot([1, 2, 3, 4, 5], [1, 2, 3, 4, 5])
axs[1, 0].plot([1, 2, 3, 4, 5], [5, 4, 3, 2, 1])
axs[1, 1].plot([1, 2, 3, 4, 5], [25, 16, 9, 4, 1])
# Adjust layout
plt.tight_layout()
Matplotlib includes a variety of pre-defined styles that can be used to quickly change the aesthetics
of your plots.
https://matplotlib.org/stable/gallery/style_sheets/style_sheets_reference.html
# Create a plot
plt.plot([1, 2, 3, 4, 5], [1, 4, 9, 16, 25])
plt.show()
keyboard_arrow_down Legends
Legends are critical for plots with multiple elements to help distinguish between them.
help(plt.legend)
legend(*args, **kwargs)
Place a legend on the Axes.
Call signatures::
legend()
legend(handles, labels)
legend(handles=handles)
legend(labels)
In this case, the labels are taken from the artist. You can specify
them either at artist creation or by calling the
:meth:`~.Artist.set_label` method on the artist::
or::
.. note::
Specific artists can be excluded from the automatic legend element
selection by using a label starting with an underscore, "_".
A string starting with an underscore is the default label for all
artists, so calling `.Axes.legend` without any arguments and
without setting the labels manually will result in no legend being
drawn.
This is similar to 2, but the labels are taken from the artists'
label properties. Example::
# Plot data
plt.plot([1, 2, 3, 4], [10, 15, 20, 25], label='Line 1')
plt.plot([1, 2, 3, 4], [25, 20, 15, 10], label='Line 2')
# Add a legend
plt.legend(loc="upper left")
# Show plot
plt.show()
Colors can be specified in various ways in Matplotlib, such as by name, hexadecimal code, or RGB
tuple.
# Plot with specific colors
plt.plot([1, 2, 3, 4], [10, 20, 30, 40], color='red', label="color") # Using color name
plt.plot([1, 2, 3, 4], [40, 30, 20, 10], color='#00FF00', label="hex") # Using hexadecimal
plt.legend()
# Show plot
plt.show()
Adjusting the line width can make a plot element stand out.
# Show plot
plt.show()
keyboard_arrow_down Line Types
The style of the line (solid, dashed, dotted, etc.) can be set to distinguish different plots.
https://matplotlib.org/stable/gallery/lines_bars_and_markers/linestyles.html
# Show plot
plt.show()
keyboard_arrow_down Markers
Markers can be used to highlight individual data points on a line or scatter plot.
https://matplotlib.org/stable/api/markers_api.html
# Show plot
plt.show()
You can combine line styles, markers, and colors for more detailed customization.
# Plot combining line styles, markers, and colors
plt.plot([1, 2, 3, 4], [10, 20, 30, 40], linestyle='--', marker='o', color='blue')
# Show plot
plt.show()
# Show plot
plt.show()
keyboard_arrow_down Using the zorder Parameter
# Show plot
plt.show()
# Data
categories = ['Category A', 'Category B', 'Category C']
values = [10, 15, 7]
# Show plot
plt.show()
Example: Creating a Horizontal Bar Graph Sometimes data is better represented horizontally,
especially if category names are long.
# Data
categories = ['Category A', 'Category B', 'Category C']
values = [10, 15, 7]
# Show plot
plt.show()
Customizing the colors and borders can help in distinguishing bars, especially in presentations.
help(plt.bar)
The bars are positioned at *x* with the given *align*\ment. Their
dimensions are given by *height* and *width*. The vertical baseline
is *bottom* (default 0).
Many parameters can take either a single value applying to all bars
or a sequence of values, one for each bar.
Parameters
----------
x : float or array-like
The x coordinates of the bars. See also *align* for the
alignment of the bars to the coordinates.
To align the bars on the right edge pass a negative *width* and
``align='edge'``.
Returns
-------
`.BarContainer`
Container with all the bars and optionally errorbars.
Other Parameters
----------------
color : color or list of color, optional
The colors of the bar faces.
# Data
categories = ['Category A', 'Category B', 'Category C']
values = [10, 15, 7]
# Creating bar graph
plt.bar(categories, values, color=['red', 'green', 'blue'], edgecolor='black')
# Show plot
plt.show()
Stacked bar graphs are useful to show segmented data within the same category.
# Data
categories = ['Category A', 'Category B', 'Category C']
values1 = [10, 15, 7]
values2 = [5, 3, 2]
# Show plot
plt.show()
Grouped bar graphs show multiple data groups side by side for easy comparison.
# Data
categories = ['Category A', 'Category B', 'Category C']
values1 = [10, 15, 7]
values2 = [5, 3, 2]
x = np.arange(len(categories)) # the label locations
# Show plot
plt.show()
Error bars can be used to indicate the variability of data and are often necessary for scientific
plotting.
# Data
categories = ['Category A', 'Category B', 'Category C']
values = [10, 15, 7]
errors = [1, 2, 1.5]
# Show plot
plt.show()