0% found this document useful (0 votes)
24 views15 pages

Unit II Lecturer Notes

Uploaded by

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

Unit II Lecturer Notes

Uploaded by

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

Unit II: Visualizing Using Matplotlib

create a custom legend with color boxes in Matplotlib using patches.

Patch and plt.legend. Below is an example demonstrating how to achieve this:

python

Copy code
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches

# Create some sample data


categories = ['Category A', 'Category B', 'Category C']
colors = ['red', 'green', 'blue']

# Create a figure and axis


fig, ax = plt.subplots()

# Plot the data


for i, category in enumerate(categories):
ax.bar(i, i+1, color=colors[i], label=category)

# Create legend patches with color boxes


legend_patches = [mpatches.Patch(color=colors[i], label=categories[i]) for i in range(len(categories))]

# Add the legend to the plot


plt.legend(handles=legend_patches, title="Legend")

# Show the plot


plt.show()
Explanation:
mpatches.Patch: This creates a colored box for each category.
handles: This is where you pass the colored patches to plt.legend.
label: Label for each category.
title: Adds a title to the legend.
This will create a plot with bars, and a custom legend with color boxes for each category.

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

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy