0% found this document useful (0 votes)
4 views

Unit II lecturer notes

This document provides a comprehensive guide on using Matplotlib for data visualization in Python, covering the basics of importing the library, creating and customizing various types of plots such as line plots, histograms, density plots, and contour plots. It also explains how to visualize errors using error bars and shaded regions, as well as the importance of legends and colors in histograms. Additionally, it includes code examples for practical implementation of these concepts.

Uploaded by

kokilal
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Unit II lecturer notes

This document provides a comprehensive guide on using Matplotlib for data visualization in Python, covering the basics of importing the library, creating and customizing various types of plots such as line plots, histograms, density plots, and contour plots. It also explains how to visualize errors using error bars and shaded regions, as well as the importance of legends and colors in histograms. Additionally, it includes code examples for practical implementation of these concepts.

Uploaded by

kokilal
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 28

Unit II: Visualizing Using Matplotlib

IMPORTING MATPLOTLIB

To begin using Matplotlib in Python, the first step is importing it into your Python environment.
Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in
Python. The core module for creating visualizations is pyplot, and it is typically imported for plotting.

Basic Import of Matplotlib

The most common import statement for Matplotlib is:

python

Copy code

import matplotlib.pyplot as plt

matplotlib is the main package.

pyplot is a sub-module within matplotlib that provides a MATLAB-like interface for creating plots and
charts.

plt is an alias often used for matplotlib.pyplot, making it shorter and more convenient to reference.

Other Common Import Statements

Importing entire Matplotlib: If you need access to all the sub-modules of Matplotlib, you can import the
whole library.

python

Copy code

import matplotlib

This allows you to access not only pyplot but also other features like matplotlib.colors,
matplotlib.animation, etc.

Importing specific modules or classes: If you only need certain features from Matplotlib, you can import
them directly.

python
Copy code

from matplotlib import pyplot as plt

Or, if you want to work with specific color maps or styles:

python

Copy code

from matplotlib import cm

Setting up inline plots in Jupyter Notebooks: If you're working in a Jupyter Notebook environment and
want plots to display inline (i.e., directly below the code), use this magic command at the start of your
notebook:

python

Copy code

%matplotlib inline

This command ensures that figures and plots are displayed inside the notebook itself, rather than in
separate windows.

Importing for Interactive Environments (Tkinter or Qt): If you're working in an interactive environment
(e.g., Tkinter or PyQt), you can import Matplotlib's interactive backends to manage how figures are
displayed.

python

Copy code

import matplotlib.pyplot as plt

plt.ion() # Turn on interactive mode

Installation of Matplotlib

Before importing Matplotlib, it must be installed. You can install it using pip:

bash

Copy code

pip install matplotlib

Or, if you are using conda:


bash

Copy code

conda install matplotlib

Common Plotting with Matplotlib

Once Matplotlib is imported, you can start plotting. Here is an example of how you might create a
simple plot:

python

Copy code

import matplotlib.pyplot as plt

# Example Data

x = [1, 2, 3, 4, 5]

y = [1, 4, 9, 16, 25]

# Create a basic line plot

plt.plot(x, y)

# Add labels and title

plt.xlabel('X Axis')

plt.ylabel('Y Axis')

plt.title('Simple Plot')

# Display the plot

plt.show()

Explanation of the Example

plt.plot(x, y): Plots the data x vs y. This creates a line plot by default.

plt.xlabel('X Axis') and plt.ylabel('Y Axis'): Set the labels for the x and y axes.
plt.title('Simple Plot'): Sets a title for the plot.

plt.show(): Displays the plot on the screen.

Customizing Plots

Matplotlib is highly customizable. You can change the line style, color, markers, and much more. Here's
a brief example:

python

Copy code

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]

y = [1, 4, 9, 16, 25]

# Customizing the plot with a red dashed line and circle markers

plt.plot(x, y, 'r--o') # 'r' for red, '--' for dashed line, 'o' for circle markers

plt.xlabel('X Axis')

plt.ylabel('Y Axis')

plt.title('Customized Plot')

plt.show()

Matplotlib Sub-modules

Matplotlib has several useful sub-modules, including:

matplotlib.pyplot: Contains functions for creating various types of plots (line plots, bar plots, scatter
plots, histograms, etc.).

matplotlib.colors: Provides functions for handling color maps and color normalization.

matplotlib.figure: Used to create and manage figures (the entire window or image where plots are
drawn).

matplotlib.animation: Used for creating animated plots.

matplotlib.ticker: Useful for controlling tick formatting (e.g., on the x and y axes).
matplotlib.backends: Contains backends for displaying plots in different environments (e.g., Tkinter, Qt,
etc.).

SIMPLE LINE PLOTS

In matplotlib, a simple line plot is a basic graph that displays data points as a series of connected line
segments. It is commonly used to visualize trends or patterns over a continuous range, such as time or
ordered categories.

How to create a simple line plot in matplotlib:

Import necessary libraries:

python

import matplotlib.pyplot as plt

Prepare data: You need two sets of data: one for the x-axis (independent variable) and one for the y-axis
(dependent variable).

Example data:

python

x = [0, 1, 2, 3, 4]

y = [0, 1, 4, 9, 16]

Plot the data: Use the plt.plot() function to create a line plot.

python

plt.plot(x, y)

Add labels and title: You can enhance your plot by adding a title, and labels for the x and y axes.

python

plt.title("Simple Line Plot")

plt.xlabel("X-axis")

plt.ylabel("Y-axis")

Display the plot: Finally, use plt.show() to display the plot.

python

plt.show()

Full Example:

python

import matplotlib.pyplot as plt


# Data

x = [0, 1, 2, 3, 4]

y = [0, 1, 4, 9, 16]

# Create the plot

plt.plot(x, y)

# Add title and labels

plt.title("Simple Line Plot")

plt.xlabel("X-axis")

plt.ylabel("Y-axis")

# Show the plot

plt.show()

Customizing the Line Plot:

Line Style:

'-' for solid line (default)

'--' for dashed line

':' for dotted line

'-.' for dash-dot line

Example:

python

plt.plot(x, y, linestyle='--') # Dashed line

Line Color:

You can set the color using a string (e.g., 'r' for red, 'g' for green, etc.).

Example:

python

plt.plot(x, y, color='g') # Green line

Line Width:

Adjust the thickness of the line with linewidth.

Example:
python

plt.plot(x, y, linewidth=2) # Thicker line

Markers:

You can add markers at each data point using the marker parameter.

Example:

python

plt.plot(x, y, marker='o') # Circle markers

Example with customizations:

python

import matplotlib.pyplot as plt

x = [0, 1, 2, 3, 4]

y = [0, 1, 4, 9, 16]

# Create a customized plot

plt.plot(x, y, color='r', linestyle='--', linewidth=2, marker='o')

# Add title and labels

plt.title("Customized Line Plot")

plt.xlabel("X-axis")

plt.ylabel("Y-axis")

# Show the plot

plt.show()

VISUALIZING ERRORS

Visualizing errors in data using Matplotlib is an essential technique, especially when presenting the
uncertainty or variability of measurements. Matplotlib provides several ways to represent errors in the
form of error bars, shaded regions, or confidence intervals, which help convey the uncertainty or
potential range of data points.

1. Error Bars

Error bars show the uncertainty in the measurements along the x, y, or both axes. You can add error
bars in Matplotlib using the errorbar function.

Basic syntax for errorbar:

python

import matplotlib.pyplot as plt


# Example data

x = [1, 2, 3, 4, 5]

y = [2, 4, 6, 8, 10]

xerr = [0.1, 0.2, 0.1, 0.3, 0.2] # x-axis errors

yerr = [0.2, 0.4, 0.2, 0.3, 0.5] # y-axis errors

plt.errorbar(x, y, xerr=xerr, yerr=yerr, fmt='o', ecolor='red', capsize=5)

plt.show()

xerr and yerr represent the error on the x-axis and y-axis, respectively.

fmt is the format for the data points (e.g., 'o' for circles).

ecolor specifies the color of the error bars.

capsize controls the size of the caps at the end of the error bars.

2. Symmetric and Asymmetric Error Bars

If the errors are asymmetric (i.e., they have different magnitudes in the positive and negative
directions), you can provide different values for the upper and lower errors.

python

xerr = [0.1, 0.2, (0.1, 0.3), 0.3, (0.2, 0.4)] # Asymmetric error on 3rd point

yerr = [0.2, (0.3, 0.5), 0.2, 0.3, (0.4, 0.6)] # Asymmetric error on 2nd and 5th points

plt.errorbar(x, y, xerr=xerr, yerr=yerr, fmt='o', ecolor='blue', capsize=5)

plt.show()

In this case, (lower, upper) is used to specify asymmetric errors.

3. Shaded Regions (Confidence Intervals)

Another way to visualize errors or uncertainty is to plot a shaded region, which can represent things like
confidence intervals or error bands.

Here’s an example of adding a shaded region:

python

import numpy as np

import matplotlib.pyplot as plt

x = np.linspace(0, 10, 100)

y = np.sin(x)

y_err = 0.1 + 0.2 * np.sqrt(x)


plt.plot(x, y, label='sin(x)')

plt.fill_between(x, y - y_err, y + y_err, color='orange', alpha=0.3, label='Error region')

plt.legend()

plt.show()

In this example:

fill_between creates a shaded region between y - y_err and y + y_err to indicate the uncertainty range.

4. Standard Deviation or Error Bars on a Line Plot

You can combine error bars with line plots to visualize errors at various points of the data.

python

x = np.linspace(0, 10, 20)

y = np.cos(x)

yerr = 0.2 + 0.1 * np.sqrt(x) # Error increases as x increases

plt.plot(x, y, label='cos(x)')

plt.errorbar(x, y, yerr=yerr, fmt='o', color='blue', ecolor='red', capsize=5, label='Error bars')

plt.legend()

plt.show()

5. Multiple Error Bars

Sometimes, you may want to show multiple types of errors, such as different error bars for different
sources of uncertainty. For example, if you have random error and systematic error:

python

x = np.linspace(0, 10, 10)

y = np.exp(-0.1 * x)

random_error = 0.1 * np.random.rand(10)

systematic_error = 0.2

plt.errorbar(x, y, yerr=[random_error, systematic_error], fmt='o', ecolor='green', capsize=5)

plt.show()

The random_error is added as random uncertainty.

The systematic_error is added as a constant error for all points.

DENSITY AND CONTOUR PLOTS


Density and contour plots are used to visualize the distribution of data and help understand the
relationships between different variables. Both plots provide insights into the "shape" of the data, with
contour plots being particularly useful in visualizing the gradients of a 2D data set.

1. Density Plots (Kernel Density Estimate, KDE)

A density plot is a smoothed version of a histogram, providing a continuous estimate of the probability
density function of a random variable. It helps to visualize the distribution of data points in a more
continuous manner.

Usage: You typically use a density plot when you want to show the distribution of data and identify
patterns such as multi-modal distributions, peaks, and the spread of data.

How to create: In Matplotlib, a density plot is often created using seaborn.kdeplot() or matplotlib's
hist2d() function with density normalization.

Example:

python

import matplotlib.pyplot as plt

import seaborn as sns

import numpy as np

# Generate random data

data = np.random.randn(1000)

# Plot the density

sns.kdeplot(data, shade=True)

plt.title("Density Plot")

plt.show()

In the above example, seaborn.kdeplot generates a smooth curve that represents the estimated density
of the data.

2. Contour Plots

A contour plot is used to represent three-dimensional data in two dimensions, where contour lines or
filled regions represent constant values of a function over the data domain. It is useful for understanding
the structure of the data and detecting areas with higher or lower values.
Usage: Contour plots are used in situations where you want to visualize how a value varies across two
variables (typically spatial data or other 2D measurements), for example, in meteorology to show
altitude lines or in data science for visualizing decision boundaries in machine learning.

How to create: In Matplotlib, the function plt.contour() is used to create contour lines, and
plt.contourf() is used for filled contour plots.

Example:

python

import matplotlib.pyplot as plt

import numpy as np

# Create a grid of x, y values

x = np.linspace(-3.0, 3.0, 100)

y = np.linspace(-3.0, 3.0, 100)

X, Y = np.meshgrid(x, y)

# Define the function to visualize

Z = np.exp(-X**2 - Y**2) # Example: a Gaussian function

# Create a contour plot

plt.contour(X, Y, Z, 20) # 20 contour levels

plt.title("Contour Plot")

plt.xlabel("X-axis")

plt.ylabel("Y-axis")

plt.colorbar() # Adds a color bar to the plot

plt.show()

In the example above:

X, Y are meshgrid arrays of values in 2D space.

Z is a function evaluated at each point in the grid.

plt.contour() draws contour lines at intervals of Z.

If you want filled contour regions instead of lines, you can use plt.contourf().
Example with filled contour:

python

plt.contourf(X, Y, Z, 20, cmap='viridis') # Filled contour with color map

plt.colorbar()

plt.title("Filled Contour Plot")

plt.show()

Key Differences Between Density and Contour Plots:

Density Plots:

Typically represent the distribution of a single variable (1D data), or in the case of a 2D density plot, the
density of points in a 2D space.

Often visualized as smoothed curves, histograms, or heatmaps.

Contour Plots:

Represent the relationship between two variables in 2D space, showing how a function or quantity
changes across that space.

Show contours (lines or filled regions) that indicate constant values over the plane.

HISTOGRAM – LEGENDS- COLORS

When you're creating histograms in Matplotlib, a powerful plotting library in Python, the concepts of
histogram, legends, and colors are important for effectively visualizing and distinguishing the data.

1. Histogram
A histogram is a graphical representation of the distribution of numerical data. It’s constructed by
dividing the data into bins (intervals) and counting the number of data points that fall into each bin.

In Matplotlib, you can create histograms using plt.hist() or ax.hist(), where:

x: The data you want to plot.


bins: The number of bins or the bin edges. You can specify this as an integer (the number of bins) or a
list of edges.
density: A boolean that normalizes the histogram so that the area under the histogram sums to 1 (useful
for probability distributions).
color: The color of the bars in the histogram.
edgecolor: The color of the edges of the bars.
Example:
python
import matplotlib.pyplot as plt
import numpy as np
data = np.random.randn(1000)
# Create histogram
plt.hist(data, bins=30, color='skyblue', edgecolor='black')
plt.title('Histogram Example')
plt.xlabel('Value')
plt.ylabel('Frequency')
plt.show()
2. Legends
Legends are essential for labeling the data series in your plot, especially when you're plotting multiple
datasets (for example, two histograms on the same plot). Legends explain what each color, line, or
marker represents.

In Matplotlib, you can add legends using plt.legend(). Each plot element (like a line or a histogram) can
be given a label, which can then be included in the legend.

Example:
python
import matplotlib.pyplot as plt
import numpy as np
data1 = np.random.randn(1000)
data2 = np.random.randn(1000)
# Plot two histograms with legends
plt.hist(data1, bins=30, alpha=0.5, label='Data 1')
plt.hist(data2, bins=30, alpha=0.5, label='Data 2')

# Adding legend
plt.legend()

plt.title('Histogram with Legends')


plt.xlabel('Value')
plt.ylabel('Frequency')
plt.show()
3. Colors
Colors play a key role in distinguishing different datasets or categories in a plot. In histograms, colors can
be used to represent different groups of data or different datasets. Matplotlib provides a variety of ways
to specify colors for your plots, from named colors to RGB values or even colormaps.
Color Options:
Named Colors: You can use standard color names like 'red', 'blue', 'green', 'orange', etc.
Hexadecimal Colors: You can specify colors using hexadecimal strings like '#FF5733'.
RGB Values: You can define a color using RGB values, like (0.1, 0.2, 0.5) for a blue shade.
Colormaps: You can use colormaps to assign colors based on some scale or continuous values.
For histograms, the color argument controls the color of the bars, and the edgecolor argument controls
the color of the edges of the bars. Additionally, if you want to color bars based on values, you can use a
colormap.

Example of Named and RGB Colors:


python
import matplotlib.pyplot as plt
import numpy as np
data1 = np.random.randn(1000)
data2 = np.random.randn(1000)
# Plot histograms with different colors
plt.hist(data1, bins=30, color='skyblue', edgecolor='black', alpha=0.7, label='Data 1')
plt.hist(data2, bins=30, color=(0.1, 0.2, 0.5), edgecolor='black', alpha=0.7, label='Data 2')

# Adding legend
plt.legend()
plt.title('Histogram with Custom Colors')
plt.xlabel('Value')
plt.ylabel('Frequency')
plt.show()
4. Coloring Bars Based on Value (Colormaps)
If you want to color the bars based on their height or frequency, you can use a colormap. Matplotlib
supports several built-in colormaps, which can be applied to your histogram.

For example, you can map the height of the bars to a color scale using the cmap argument. To do this,
you would typically calculate the histogram, then apply the colormap to each bar based on its height.

Example with Colormap:


python
import matplotlib.pyplot as plt
import numpy as np
data = np.random.randn(1000)

# Create histogram data


counts, bins = np.histogram(data, bins=30)

# Normalize counts to get colors


norm = plt.Normalize(min(counts), max(counts))

# Plot histogram with color gradient based on counts


plt.bar(bins[:-1], counts, width=np.diff(bins), align='edge',
color=plt.cm.viridis(norm(counts)))

plt.title('Histogram with Colormap')


plt.xlabel('Value')
plt.ylabel('Frequency')
plt.show()
5. Additional Customizations
Alpha: Controls the transparency of the bars. An alpha value of 1 means fully opaque, while 0 means
fully transparent. You can use this for overlapping histograms.
Stacked Histograms: You can stack multiple datasets in one histogram to compare distributions. This can
be done by setting the stacked argument to True.
python
plt.hist([data1, data2], bins=30

Subplots in Matplotlib
When visualizing data using Matplotlib, you often need to create multiple plots in a single figure to
compare trends or analyze different aspects of the data. Matplotlib's subplots feature provides a simple
way to create and manage multiple plots within the same figure.

Basic Concepts:
A figure is the overall window or page on which the plots appear.
A subplot is one plot among many on a figure.
The subplots function allows you to create a grid of subplots, and you can specify the number of rows
and columns.
1. Basic Syntax of plt.subplots()
python
Copy code
import matplotlib.pyplot as plt

# Create a figure with subplots (nrows, ncols)


fig, ax = plt.subplots(nrows=2, ncols=2)

# Plotting example
ax[0, 0].plot([1, 2, 3], [4, 5, 6])
ax[0, 1].plot([1, 2, 3], [6, 5, 4])
ax[1, 0].plot([1, 2, 3], [7, 8, 9])
ax[1, 1].plot([1, 2, 3], [9, 8, 7])

plt.show()
Explanation:

nrows and ncols define the number of rows and columns for subplots, respectively.
ax is a 2D array of Axes objects where you can access individual subplots by indexing them (e.g., ax[0,
0]).
2. Tight Layout
The tight_layout() function automatically adjusts subplot parameters to give some padding between
plots and avoid overlapping.
python
Copy code
fig, ax = plt.subplots(2, 2)
plt.tight_layout()
plt.show()
3. Sharing Axes in Subplots
Sometimes it is useful to have subplots that share the same x-axis or y-axis for easy comparison. You can
use the sharex and sharey options.

python
Copy code
fig, ax = plt.subplots(2, 2, sharex=True, sharey=True)

# Plotting example
ax[0, 0].plot([1, 2, 3], [4, 5, 6])
ax[0, 1].plot([1, 2, 3], [6, 5, 4])
ax[1, 0].plot([1, 2, 3], [7, 8, 9])
ax[1, 1].plot([1, 2, 3], [9, 8, 7])

plt.tight_layout()
plt.show()
Explanation:

sharex=True ensures all subplots share the same x-axis.


sharey=True ensures all subplots share the same y-axis.
4. Customizing Subplot Size and Aspect Ratio
You can customize the size of the figure and subplots by using the figsize argument and the gridspec
module.

python
Copy code
fig, ax = plt.subplots(2, 2, figsize=(8, 6))
plt.show()
Explanation:

figsize=(width, height) allows you to control the size of the entire figure in inches.
5. Handling Subplots in a Loop
You can also create subplots in a loop when working with dynamic data or a large number of plots.

python
Copy code
fig, ax = plt.subplots(2, 2)
for i in range(2):
for j in range(2):
ax[i, j].plot([1, 2, 3], [4 * i + j, 5 * i + j, 6 * i + j])
plt.tight_layout()
plt.show()
6. 1xN and Nx1 Subplots (Single Row or Single Column)
For linear arrangements of subplots, such as all plots in one row or one column, plt.subplots() makes it
easy to manage these cases.

Example for a 1x3 subplot layout:


python
Copy code
fig, ax = plt.subplots(1, 3) # 1 row, 3 columns
ax[0].plot([1, 2, 3], [1, 2, 3])
ax[1].plot([1, 2, 3], [4, 5, 6])
ax[2].plot([1, 2, 3], [7, 8, 9])

plt.tight_layout()
plt.show()
Example for a 3x1 subplot layout:
python
Copy code
fig, ax = plt.subplots(3, 1) # 3 rows, 1 column
ax[0].plot([1, 2, 3], [1, 2, 3])
ax[1].plot([1, 2, 3], [4, 5, 6])
ax[2].plot([1, 2, 3], [7, 8, 9])

plt.tight_layout()
plt.show()
7. Removing Unused Subplots
If you create a grid of subplots but don't need all of them, you can hide unused subplots.

python
Copy code
fig, ax = plt.subplots(2, 2)

# Removing an unused subplot


ax[1, 1].axis('off')
plt.tight_layout()
plt.show()
8. Combining gridspec for Complex Layouts
You can use GridSpec for more complex layouts where subplots of different sizes are required.

python
Copy code
import matplotlib.gridspec as gridspec

fig = plt.figure()
gs = gridspec.GridSpec(3, 3)

ax1 = fig.add_subplot(gs[0, :]) # First row, spans all columns


ax2 = fig.add_subplot(gs[1, :-1]) # Second row, all except the last column
ax3 = fig.add_subplot(gs[1:, -1]) # Second and third row, last column
ax4 = fig.add_subplot(gs[-1, 0]) # Last row, first column
ax5 = fig.add_subplot(gs[-1, -2]) # Last row, second column

plt.tight_layout()
plt.show()
9. Adding Titles, Labels, and Legends to Subplots
You can add titles and labels to individual subplots for better clarity:

python
Copy code
fig, ax = plt.subplots(2, 2)

ax[0, 0].plot([1, 2, 3], [4, 5, 6])


ax[0, 0].set_title('First Plot')
ax[0, 0].set_xlabel('X-axis')
ax[0, 0].set_ylabel('Y-axis')

ax[1, 1].plot([1, 2, 3], [7, 8, 9])


ax[1, 1].legend(['Data'])

plt.tight_layout()
plt.show()
10. Saving Figures with Subplots
To save a figure with subplots, use the savefig() function.

python
Copy code
fig, ax = plt.subplots(2, 2)
plt.savefig('my_subplots_figure.png')
Conclusion:
The subplots function in Matplotlib is a powerful tool for creating complex visualizations with multiple
plots. Using features like sharex, sharey, tight_layout(), and GridSpec, you can customize and arrange
your plots efficiently.

Text And Annotations


1. Adding Text in Matplotlib
The text() function allows you to add arbitrary text to the plot at any position.

Basic Syntax:

python
Copy code
plt.text(x, y, s, fontsize=12, color='black')
x, y: The coordinates where the text will appear.
s: The text string itself.
fontsize: (optional) Controls the font size of the text.
color: (optional) Specifies the color of the text.
Example:

python
Copy code
import matplotlib.pyplot as plt

# Sample plot
plt.plot([1, 2, 3], [4, 5, 6])

# Add text
plt.text(2, 5, 'Data point (2, 5)', fontsize=12, color='red')

plt.show()
2. Adding Annotations in Matplotlib
The annotate() function allows you to add text annotations that are connected to a specific data point.

Basic Syntax:

python
Copy code
plt.annotate(text, xy, xytext=None, arrowprops=None)
text: The annotation text.
xy: The coordinates of the point you want to annotate (where the arrow will point).
xytext: (optional) The position of the text.
arrowprops: (optional) A dictionary of properties to customize the arrow.
Example with Arrow:

python
Copy code
import matplotlib.pyplot as plt

# Sample plot
plt.plot([1, 2, 3], [4, 5, 6])

# Add annotation
plt.annotate('Important point', xy=(2, 5), xytext=(3, 4),
arrowprops=dict(facecolor='black', shrink=0.05))

plt.show()
Customization Options for Annotations
Text properties: You can change font size, color, style, etc.
Arrow properties: You can customize the arrow appearance with properties like arrowstyle, color,
linewidth, etc.
Example of Custom Arrow:

python
Copy code
plt.annotate('Critical point', xy=(2, 5), xytext=(3, 4),
arrowprops=dict(facecolor='blue', arrowstyle='->', linewidth=2))
3. Text Box (Bounding Box)
Sometimes, you want to place text inside a box for better visibility.

python
Copy code
plt.text(2, 5, 'Data point (2, 5)', fontsize=12, bbox=dict(facecolor='yellow', alpha=0.5))
In this example, the bbox argument creates a semi-transparent yellow background behind the text.

Combining Text and Annotations in a Plot


You can use both text() and annotate() together to highlight key areas of a plot while providing detailed
explanations.

Complete Example:

python
Copy code
import matplotlib.pyplot as plt

# Data
x = [1, 2, 3]
y = [4, 5, 6]

plt.plot(x, y)

# Add text and annotation


plt.text(1, 4, 'Start Point', fontsize=10, color='green')
plt.annotate('Maximum', xy=(3, 6), xytext=(2, 5.5),
arrowprops=dict(facecolor='red', shrink=0.05))

plt.show()
This shows how you can use text and annotations to make your visualizations more informative and
aesthetically appealing.

Customization

1. Figure and Axes Customization

 Figure size: You can change the figure size using figsize.

python
Copy code
import matplotlib.pyplot as plt
plt.figure(figsize=(10, 6)) # Width: 10, Height: 6
 Multiple subplots: Use plt.subplot() or plt.subplots() for more control over
multiple plots.

python
Copy code
fig, ax = plt.subplots(2, 2, figsize=(10, 8)) # 2x2 grid of plots
2. Line and Marker Styles

 Line styles: Customize line properties like color, width, and style using parameters like
color, linewidth, and linestyle.

python
Copy code
plt.plot(x, y, color='red', linewidth=2, linestyle='--')
 Markers: Change marker style with the marker, markersize, and markerfacecolor
parameters.

python
Copy code
plt.plot(x, y, marker='o', markersize=10, markerfacecolor='blue')
3. Axes Customization

 Limits: You can set custom limits on x and y axes with plt.xlim() and plt.ylim().

python
Copy code
plt.xlim([0, 10])
plt.ylim([0, 100])
 Ticks: Customize tick marks using plt.xticks() and plt.yticks(), where you can
control locations and labels.

python
Copy code
plt.xticks([0, 2, 4, 6, 8, 10], ['A', 'B', 'C', 'D', 'E', 'F'])
4. Labels and Titles

 Title and labels: Add a title, x-axis, and y-axis labels using plt.title(),
plt.xlabel(), and plt.ylabel().

python
Copy code
plt.title('Sample Plot')
plt.xlabel('X Axis')
plt.ylabel('Y Axis')
 Font properties: Customize the font style, size, and weight for titles and labels.

python
Copy code
plt.title('Sample Plot', fontsize=16, fontweight='bold',
fontfamily='serif')
5. Legends

 Add legends: Use plt.legend() to add a legend for the plot.

python
Copy code
plt.plot(x, y, label='Data 1')
plt.legend(loc='upper left')
 Legend customization: You can control the location, frame, and font size of the legend.

python
Copy code
plt.legend(loc='best', fontsize=12, frameon=False)
6. Gridlines

 Enable grid: You can add gridlines using plt.grid().

python
Copy code
plt.grid(True, linestyle='--', color='gray', alpha=0.7)
7. Annotations

 Text annotations: Use plt.text() or plt.annotate() to place custom text on the plot.

python
Copy code
plt.annotate('Important Point', xy=(5, 50), xytext=(6, 60),
arrowprops=dict(facecolor='black', arrowstyle='->'))
8. Colormaps and Colorbars

 Colormap: For heatmaps or other color-based plots, you can use built-in colormaps.

python
Copy code
plt.imshow(data, cmap='viridis')
 Colorbar: Add a colorbar to explain color scales.
python
Copy code
plt.colorbar()
9. Stylesheets

 Pre-defined styles: Use predefined styles such as ggplot, seaborn, etc.

python
Copy code
plt.style.use('ggplot')
10. Saving Figures

 Save plots: Save your figure with plt.savefig().

python
Copy code
plt.savefig('plot.png', dpi=300, bbox_inches='tight')
Example Putting it All Together
python
Copy code
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 10, 100)


y = np.sin(x)

plt.figure(figsize=(10, 6))
plt.plot(x, y, label='sin(x)', color='blue', linewidth=2, linestyle='--',
marker='o')

plt.title('Sine Wave Example', fontsize=16, fontweight='bold')


plt.xlabel('X Axis', fontsize=12)
plt.ylabel('Y Axis', fontsize=12)

plt.xlim(0, 10)
plt.ylim(-1.5, 1.5)

plt.grid(True, linestyle='--', color='gray', alpha=0.7)


plt.legend(loc='upper right', fontsize=12)
plt.savefig('custom_plot.png', dpi=300, bbox_inches='tight')

plt.show()

Three Dimensional Plotting


In Matplotlib, 3D plotting is enabled by importing the Axes3D class from mpl_toolkits.mplot3d. The
process involves creating a figure and then adding a 3D subplot to it, which can be used for various types
of 3D visualizations.

Here's a basic example of how to create a 3D plot using Matplotlib:

Steps for 3D plotting:


Import necessary libraries.
Create a figure object.
Add a 3D subplot to the figure.
Generate data.
Plot the data in 3D.
Example 1: 3D Line Plot
python
Copy code
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D

# Data generation
x = np.linspace(-5, 5, 100)
y = np.sin(x)
z = np.cos(x)

# Create a 3D plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# Plot the data


ax.plot(x, y, z)

# Labels
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
ax.set_zlabel('Z axis')

plt.show()
Example 2: 3D Surface Plot
A surface plot is used to visualize a 3D surface.

python
Copy code
# Data generation
X = np.linspace(-5, 5, 100)
Y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(X, Y)
Z = np.sin(np.sqrt(X**2 + Y**2))

# Create a 3D plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# Plot the surface


ax.plot_surface(X, Y, Z, cmap='viridis')

# Labels
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
ax.set_zlabel('Z axis')

plt.show()
Example 3: 3D Scatter Plot
python
Copy code
# Data generation
x = np.random.rand(100)
y = np.random.rand(100)
z = np.random.rand(100)

# Create a 3D plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# Plot the scatter plot


ax.scatter(x, y, z, c='r', marker='o')

# Labels
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
ax.set_zlabel('Z axis')

plt.show()
Customization
You can customize colors, labels, title, and viewing angles using:

ax.view_init(elev, azim) – sets the elevation and azimuth angles of the plot.
ax.set_title('Title') – adds a title to the plot.
ax.set_xlim([xmin, xmax]), ax.set_ylim([ymin, ymax]), ax.set_zlim([zmin, zmax]) – to control the axes
limits.

Geographic Data With Basemap

1. Install the necessary libraries


Make sure you have basemap, matplotlib, and numpy installed. You can install them using pip:
bash
Copy code
pip install basemap matplotlib numpy
2. Basic Map Plotting with Basemap
Here is an example where we visualize a world map using Basemap and Matplotlib.

python
Copy code
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap

# Set up the figure


plt.figure(figsize=(12, 8))

# Create a Basemap instance with desired projection


m = Basemap(projection='mill', # Projection type (Miller cylindrical projection)
llcrnrlat=-60, urcrnrlat=90, # Latitude range (lower and upper corners)
llcrnrlon=-180, urcrnrlon=180, # Longitude range (lower and upper corners)
resolution='c') # Resolution of coastline ('c' is for crude)

# Draw coastlines and countries


m.drawcoastlines()
m.drawcountries()

# Optionally, draw parallels and meridians (grid lines)


m.drawparallels(range(-90, 91, 30))
m.drawmeridians(range(-180, 181, 60))

# Show the plot


plt.title("Basic World Map with Basemap")
plt.show()
3. Plotting Geographic Data
Suppose you have geographic coordinates (latitude and longitude) and you want to plot them on the
map. Here's how you can do it.

python
Copy code
import numpy as np

# Example data: random geographic coordinates


lats = np.random.uniform(low=-60, high=90, size=100) # latitudes
lons = np.random.uniform(low=-180, high=180, size=100) # longitudes

# Convert latitudes and longitudes to x and y coordinates using the Basemap instance
x, y = m(lons, lats)

# Plot data points on the map


m.scatter(x, y, s=10, c='red', marker='o', alpha=0.7, zorder=5)

# Show the plot


plt.title("Geographic Data Points on a World Map")
plt.show()
4. Customizing the Map
You can customize the appearance of your map by changing parameters like:

Projection: There are many projections available such as cyl (Cylindrical Equidistant), merc (Mercator),
ortho (Orthographic), etc.
Resolution: The resolution of coastline data can be 'c' (crude), 'l' (low), 'i' (intermediate), 'h' (high), and 'f'
(full).
Shading: You can use functions like m.bluemarble(), m.shadedrelief(), or m.etopo() to display shaded
relief or topography.
For example:

python
Copy code
# Shaded relief map with a different projection (Mercator)
m = Basemap(projection='merc',
llcrnrlat=-60, urcrnrlat=90,
llcrnrlon=-180, urcrnrlon=180,
resolution='l')

# Draw the map features


m.drawcoastlines()
m.drawcountries()
m.shadedrelief()

plt.title("Shaded Relief Map with Basemap")


plt.show()
5. Working with Shapefiles
If you want to plot shapefiles (such as country or regional boundaries), you can use
Basemap.readshapefile():

python
Copy code
# Assuming you have a shapefile of countries
m.readshapefile('shapefiles/countries', 'countries')

# Plot the map with shapefile data


m.drawcoastlines()
m.drawcountries()

plt.title("Map with Shapefile Data")


plt.show()

Visualization with Seaborn

Seaborn is a powerful data visualization library built on top of Matplotlib. It provides an interface for
creating informative and attractive statistical graphics. While Matplotlib is more versatile and gives
greater control over individual elements, Seaborn simplifies common tasks and produces aesthetically
pleasing default plots.

How Seaborn and Matplotlib Work Together


Seaborn is built on top of Matplotlib, meaning you can use Matplotlib functions alongside Seaborn
plots. For instance, you can create a Seaborn plot and then use Matplotlib to adjust specific aspects
like figure size, axis labels, or titles.

Importing Seaborn and Matplotlib


python
Copy code
import seaborn as sns
import matplotlib.pyplot as plt
Example: Using Seaborn with Matplotlib
Creating a Simple Seaborn Plot
Let’s start with a simple plot using Seaborn:

python
Copy code
# Load an example dataset
tips = sns.load_dataset("tips")

# Create a simple scatter plot with Seaborn


sns.scatterplot(x="total_bill", y="tip", data=tips)

# Show the plot


plt.show()
In this case, sns.scatterplot() creates a scatter plot, and plt.show() from Matplotlib renders the plot.

Customizing with Matplotlib


You can still use Matplotlib’s functions to customize Seaborn plots. For example, adding titles, labels,
or changing figure size:

python
Copy code
plt.figure(figsize=(8, 6)) # Adjust the figure size with Matplotlib
sns.scatterplot(x="total_bill", y="tip", data=tips)

# Add labels and title using Matplotlib


plt.title("Total Bill vs Tip Amount")
plt.xlabel("Total Bill ($)")
plt.ylabel("Tip ($)")

plt.show()
Here, we used plt.figure() to adjust the size of the plot and then added titles and labels using
Matplotlib.

Common Seaborn Plots with Matplotlib


Histogram (sns.histplot): A simple histogram to show the distribution of a variable.

python
Copy code
plt.figure(figsize=(8, 6))
sns.histplot(tips['total_bill'], bins=20, kde=True) # kde adds a smooth line
plt.title("Distribution of Total Bill")
plt.xlabel("Total Bill")
plt.ylabel("Frequency")
plt.show()
Box Plot (sns.boxplot): Useful for visualizing the spread and outliers in a dataset.

python
Copy code
plt.figure(figsize=(8, 6))
sns.boxplot(x="day", y="total_bill", data=tips)
plt.title("Box Plot of Total Bill by Day")
plt.show()
Heatmap (sns.heatmap): Often used to visualize correlation matrices or other grid data.
python
Copy code
plt.figure(figsize=(8, 6))
corr = tips.corr()
sns.heatmap(corr, annot=True, cmap="coolwarm")
plt.title("Correlation Heatmap of Tips Dataset")
plt.show()
Overlaying Seaborn and Matplotlib
You can overlay Matplotlib and Seaborn plots:

python
Copy code
plt.figure(figsize=(8, 6))

# Seaborn plot
sns.histplot(tips['total_bill'], bins=20, color='blue', label="Seaborn")

# Matplotlib plot overlaid


plt.hist(tips['total_bill'], bins=20, color='red', alpha=0.3, label="Matplotlib")

# Add legend
plt.legend()

plt.title("Total Bill Distribution: Seaborn vs Matplotlib")


plt.show()
In this example, Seaborn and Matplotlib are used together in the same plot, giving a good sense of
how both libraries can complement each other.

By combining the simplicity of Seaborn with the fine-tuning controls of Matplotlib, you can create
sophisticated and visually appealing visualizations for your data analysis.

You might also like