[go: up one dir, main page]

0% found this document useful (0 votes)
3 views29 pages

Mat Plot

Matplotlib is a versatile Python library for creating static, animated, and interactive visualizations, originally developed in 2003. It allows users to easily generate a variety of plots, such as linear and quadratic equations, using simple code. The library also supports creating figures with multiple axes and subplots for organized data presentation.

Uploaded by

baluduvamsi2000
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views29 pages

Mat Plot

Matplotlib is a versatile Python library for creating static, animated, and interactive visualizations, originally developed in 2003. It allows users to easily generate a variety of plots, such as linear and quadratic equations, using simple code. The library also supports creating figures with multiple axes and subplots for organized data presentation.

Uploaded by

baluduvamsi2000
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

keyboard_arrow_down Introduction to Matplotlib

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:

!pip install matplotlib

Requirement already satisfied: matplotlib in /usr/local/lib/python3.10/dist-pack


Requirement already satisfied: contourpy>=1.0.1 in /usr/local/lib/python3.10/dis
Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.10/dist-pa
Requirement already satisfied: fonttools>=4.22.0 in /usr/local/lib/python3.10/di
Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.10/di
Requirement already satisfied: numpy>=1.20 in /usr/local/lib/python3.10/dist-pac
Requirement already satisfied: packaging>=20.0 in /usr/local/lib/python3.10/dist
Requirement already satisfied: pillow>=6.2.0 in /usr/local/lib/python3.10/dist-p
Requirement already satisfied: pyparsing>=2.3.1 in /usr/local/lib/python3.10/dis
Requirement already satisfied: python-dateutil>=2.7 in /usr/local/lib/python3.10
Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.10/dist-packag

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 matplotlib.pyplot as 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.

x = np.linspace(start=-10, stop=10, num=400)

2. Define the linear equation: Specify the slope (m) and intercept (c).

m = 2 # Slope
c = 3 # Intercept
y = m * x + c

3. Plot the equation: Use Matplotlib to plot the line.

plt.plot(x, y, label='y = 2x + 3')


plt.title('Plot of the Linear Equation')
plt.xlabel('x')
plt.ylabel('y')
plt.xlim(0,10) # Lower Limit, Upper Limit
plt.ylim(0,20) # Lower Limit, Upper Limit
plt.grid(True)
plt.legend()
plt.savefig('linear-equation.png')
plt.show()
In this code:

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.grid(True) enables a grid to make reading the plot easier.

plt.savefig() allows you to save the figure in various file formats such as PNG, JPEG, SVG,
PDF, and more.

plt.show() displays the plot.

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.

Here's how you can plot the quadratic equation y = x^2 - 4x + 4:

# Define the coefficients


a = 1
b = -4
c = 4

# Generate x values
x = np.linspace(-1, 7, 400)

# Calculate y values using the quadratic equation


y = a * x**2 + b * x + c

# Create the plot


plt.plot(x, y, label='y = x^2 - 4x + 4')

# Adding title and labels


plt.title('Plot of the Quadratic Equation')
plt.xlabel('x')
plt.ylabel('y')
plt.xlim(-5,10)
plt.ylim(0,30)

plt.legend()
# Add grid
plt.grid(True)

# Show the plot


plt.show()

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.

y = a * x**2 + b * x + c calculates the y-values based on the quadratic formula. plt.plot(x, y,


label='...') plots the equation and includes a label.

plt.title(), plt.xlabel(), and plt.ylabel() set the title and labels of the axes.

plt.grid(True) adds a grid to the plot to improve readability.

plt.show() displays the resulting plot.

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.

keyboard_arrow_down Creating a Figure

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:

# Create a figure object


fig = plt.figure()

# Add axes to the figure (left, bottom, width, height)


ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])

# Display the figure


plt.show()
keyboard_arrow_down A Detailed Example

# Creating an array of x values


x = np.linspace(0, 10, 100)
# Calculating y values based on x
y = np.sin(x)

# Create a new figure with a specific size


fig = plt.figure(figsize=(8, 6))

# Add an axes to the figure


# The list [left, bottom, width, height] defines the dimensions of the axes within the figu
ax = fig.add_axes([0.1, 0.1, 0.85, 0.85])

# Plot data on the axes


ax.plot(x, y, label='sin(x)', color='green')

# Set the title of the plot


ax.set_title('Simple Plot of sin(x)')
ax.legend()
# Set the x and y axis labels
ax.set_xlabel('x')
ax.set_ylabel('Amplitude')

# Display the figure


plt.show()
Breakdown:

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.

Double-click (or enter) to edit

Creating a Matplotlib Figure with Multiple Axes Arranged


keyboard_arrow_down at Various Positions
Overview:

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:

Figure: The entire window or the canvas for the plots.

Axes: The individual plots; each set of axes can contain its own elements like lines, labels,
ticks, and titles.

Configuring Multiple Axes:


To position axes, use fig.add_axes() with the format [left, bottom, width, height] where each value is
a fraction of the figure dimensions:

left, bottom: These determine the position of the bottom-left corner of the axes.
width, height: These determine the size of the axes.

Example Code for Linear Functions in Different Axes Positions:

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)

# Create a blank canvas


fig = plt.figure(figsize=(10, 8))

# Center plot - main plot


axes_center = fig.add_axes([0.3, 0.3, 0.4, 0.4]) # left, bottom, width, height
axes_center.plot(x, x + 1) # y = x + 1
axes_center.set_title('Center Plot: y = x + 1')

# Top plot - summary


axes_top = fig.add_axes([0.3, 0.75, 0.4, 0.2])
axes_top.plot(x, 2*x + 1) # y = 2x + 1
axes_top.set_title('Top Plot: y = 2x + 1')

# Right plot - auxiliary data


axes_right = fig.add_axes([0.75, 0.3, 0.2, 0.4])
axes_right.plot(x, 0.5*x + 1) # y = 0.5x + 1
axes_right.set_title('Right Plot: y = 0.5x + 1')

# Left plot - contextual information


axes_left = fig.add_axes([0.05, 0.3, 0.2, 0.4])
axes_left.plot(x, 3*x + 1) # y = 3x + 1
axes_left.set_title('Left Plot: y = 3x + 1')

# Bottom plot - comparative data


axes_bottom = fig.add_axes([0.3, 0.05, 0.4, 0.2])
axes_bottom.plot(x, -x + 1) # y = -x + 1
axes_bottom.set_title('Bottom Plot: y = -x + 1')

# Top Right Corner plot - highlight


axes_top_right = fig.add_axes([0.75, 0.75, 0.2, 0.2])
axes_top_right.plot(x, 4*x + 1) # y = 4x + 1
axes_top_right.set_title('Top Right Plot: y = 4x + 1')

plt.show()
# Generate x values
x = np.linspace(0, 10, 100)

# Create a blank canvas


fig = plt.figure(figsize=(10, 8))

# Center plot - main plot


axes_center = fig.add_axes([0,0, 0.4, 0.4]) # left, bottom, width, height
axes_center.plot(x, x + 1) # y = x + 1
axes_center.set_title('Center Plot: y = x + 1')

axes_example = fig.add_axes([1,1, 0.1, 0.1])


axes_example.plot(x, 4*x + 1) # y = 4x + 1
axes_example.set_title('Example Plot: y = 4x + 1')

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.

Basic Example of Using subplots():

# Create a figure and a single subplot


fig, ax = plt.subplots()

# 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()

# Show the plot


plt.show()
Adding Rows and Columns of Subplots: You can specify the number of rows and columns of
subplots in the plt.subplots() function.

Creating a 2x2 grid of subplots:

# Create a 2x2 grid of subplots


fig, axs = plt.subplots(2, 2) # 2 rows, 2 columns

# Plot data in each subplot


axs[0, 0].plot([1, 2, 3, 4, 5], [1, 4, 9, 16, 25]) # Top-left
axs[0, 1].plot([1, 2, 3, 4, 5], [1, 2, 3, 4, 5]) # Top-right
axs[1, 0].plot([1, 2, 3, 4, 5], [5, 4, 3, 2, 1]) # Bottom-left
axs[1, 1].plot([1, 2, 3, 4, 5], [25, 16, 9, 4, 1]) # Bottom-right

# Show the plot


plt.show()

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()

# Show the plot


plt.show()

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()

# Show the plot


plt.show()
keyboard_arrow_down Matplotlib Plot Styles and Customizations
Matplotlib offers extensive customization options for plots, including styles, colors, line widths, line
types, markers, and legends. Each customization enhances the readability and aesthetics of plots.

keyboard_arrow_down Plot Styles

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

# Use the 'ggplot' style


plt.style.use('ggplot')

# 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)

Help on function legend in module matplotlib.pyplot:

legend(*args, **kwargs)
Place a legend on the Axes.

Call signatures::

legend()
legend(handles, labels)
legend(handles=handles)
legend(labels)

The call signatures correspond to the following different ways to use


this method:

**1. Automatic detection of elements to be shown in the legend**

The elements to be added to the legend are automatically determined,


when you do not pass in any extra arguments.

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

ax.plot([1, 2, 3], label='Inline label')


ax.legend()

or::

line, = ax.plot([1, 2, 3])


line.set_label('Label via method')
ax.legend()

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

**2. Explicitly listing the artists and labels in the legend**

For full control of which artists have a legend entry, it is possible


to pass an iterable of legend artists followed by an iterable of
legend labels respectively::

ax.legend([line1, line2, line3], ['label1', 'label2', 'label3'])

**3. Explicitly listing the artists in the legend**

This is similar to 2, but the labels are taken from the artists'
label properties. Example::

line1, = ax.plot([1, 2, 3], label='label1')


line2, = ax.plot([1, 2, 3], label='label2')

# 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()

keyboard_arrow_down Setting Colors

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()

keyboard_arrow_down Line Widths

Adjusting the line width can make a plot element stand out.

# Plot with different line widths


plt.plot([1, 2, 3, 4], [10, 20, 30, 40], linewidth=2) # Normal width
plt.plot([1, 2, 3, 4], [40, 30, 20, 10], linewidth=8) # Thicker line

# 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

# Plot with different line types


plt.plot([1, 2, 3, 4], [10, 20, 30, 40], linestyle='-') # Solid line
plt.plot([1, 2, 3, 4], [40, 30, 20, 10], linestyle='--') # Dashed line

# 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

# Plot with markers


plt.plot([1, 2, 3, 4], [10, 20, 30, 40], marker='o') # Circle markers

# Show plot
plt.show()

keyboard_arrow_down Combining Line Styles, Markers, and Colors

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()

keyboard_arrow_down Adjusting Marker Size and Color

# Plot with customized markers


plt.plot([1, 2, 3, 4], [10, 20, 30, 40], marker='s', markersize=10, markerfacecolor='green'

# Show plot
plt.show()
keyboard_arrow_down Using the zorder Parameter

The zorder parameter determines the drawing order of plot elements.

# Plot with zorder


plt.plot([1, 2, 3, 4], [40, 30, 20, 10], color='red', linewidth=5, zorder=1) # Drawn first
plt.plot([1, 2, 3, 4], [10, 20, 30, 40], color='blue', linewidth=5, zorder=2) # Drawn on t
plt.plot([1, 2, 3, 4], [10, 13, 15, 17], color='green', linewidth=5, zorder=3) # Drawn on t

# Show plot
plt.show()

keyboard_arrow_down Matplotlib Bar Graphs


Bar graphs are a powerful tool for visualizing categorical data, where each category is represented
by a bar whose height (or length, in the case of horizontal bars) corresponds to its value. Matplotlib
provides extensive functionality to customize bar graphs according to your data visualization
needs.

Example: Creating a Simple Bar Graph

# Data
categories = ['Category A', 'Category B', 'Category C']
values = [10, 15, 7]

# Creating bar graph


plt.bar(categories, values)

# Adding title and labels


plt.title('Basic Bar Graph')
plt.xlabel('Categories')
plt.ylabel('Values')

# 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]

# Creating horizontal bar graph


plt.barh(categories, values, color='skyblue')

# Adding title and labels


plt.title('Horizontal Bar Graph')
plt.xlabel('Values')
plt.ylabel('Categories')

# Show plot
plt.show()

Example: Bars with Different Colors and Borders

Customizing the colors and borders can help in distinguishing bars, especially in presentations.

help(plt.bar)

Help on function bar in module matplotlib.pyplot:

bar(x, height, width=0.8, bottom=None, *, align='center', data=None, **kwargs)


Make a bar plot.

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.

height : float or array-like


The height(s) of the bars.

width : float or array-like, default: 0.8


The width(s) of the bars.

bottom : float or array-like, default: 0


The y coordinate(s) of the bottom side(s) of the bars.

align : {'center', 'edge'}, default: 'center'


Alignment of the bars to the *x* coordinates:

- 'center': Center the base on the *x* positions.


- 'edge': Align the left edges of the bars with the *x* positions.

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.

edgecolor : color or list of color, optional


The colors of the bar edges.

linewidth : float or array-like, optional


Width of the bar edge(s). If 0, don't draw edges.

tick_label : str or list of str, optional


The tick labels of the bars.
Default: None (Use default numeric labels.)

label : str or list of str, optional


A single label is attached to the resulting `.BarContainer` as a

# 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')

# Adding title and labels


plt.title('Colored Bar Graph')
plt.xlabel('Categories')
plt.ylabel('Values')

# Show plot
plt.show()

Example: Creating Stacked Bar Graphs

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]

# Creating stacked bar graph


plt.bar(categories, values1, label='Part 1')
plt.bar(categories, values2, bottom=values1, label='Part 2')

# Adding title, labels, and legend


plt.title('Stacked Bar Graph')
plt.xlabel('Categories')
plt.ylabel('Values')
plt.legend()

# Show plot
plt.show()

Example: Creating Grouped Bar Graphs

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

# Width of the bars


width = 0.35

# Creating grouped bar graph


plt.bar(x - width/2, values1, width, label='Part 1')
plt.bar(x + width/2, values2, width, label='Part 2')

# Adding title, labels, and legend


plt.title('Grouped Bar Graph')
plt.xlabel('Categories')
plt.ylabel('Values')
plt.xticks(x, categories)
plt.legend()

# Show plot
plt.show()

Example: Adding Error Bars

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]

# Creating bar graph with error bars


plt.bar(categories, values, yerr=errors, capsize=5)

# Adding title and labels


plt.title('Bar Graph with Error Bars')
plt.xlabel('Categories')
plt.ylabel('Values')

# Show plot
plt.show()

You might also like