Unit II Lecturer Notes
Unit II Lecturer Notes
python
Copy code
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
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
# 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:
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.
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)
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)
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.
Complete Example:
python
Copy code
import matplotlib.pyplot as plt
# Data
x = [1, 2, 3]
y = [4, 5, 6]
plt.plot(x, y)
plt.show()
This shows how you can use text and annotations to make your visualizations more informative and
aesthetically appealing.
Customization
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
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
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
python
Copy code
plt.style.use('ggplot')
10. Saving Figures
plt.figure(figsize=(10, 6))
plt.plot(x, y, label='sin(x)', color='blue', linewidth=2, linestyle='--',
marker='o')
plt.xlim(0, 10)
plt.ylim(-1.5, 1.5)
plt.show()
# 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')
# 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')
# 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')
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.
python
Copy code
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
python
Copy code
import numpy as np
# Convert latitudes and longitudes to x and y coordinates using the Basemap instance
x, y = m(lons, lats)
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')
python
Copy code
# Assuming you have a shapefile of countries
m.readshapefile('shapefiles/countries', 'countries')
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.
python
Copy code
# Load an example dataset
tips = sns.load_dataset("tips")
python
Copy code
plt.figure(figsize=(8, 6)) # Adjust the figure size with Matplotlib
sns.scatterplot(x="total_bill", y="tip", data=tips)
plt.show()
Here, we used plt.figure() to adjust the size of the plot and then added titles and labels using
Matplotlib.
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")
# Add legend
plt.legend()
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.