0% found this document useful (0 votes)
22 views37 pages

Matplotlib Import and Plotting Guide

The document provides a comprehensive guide on using Matplotlib for various types of plots, including line plots, scatter plots, error bars, density and contour plots, and histograms. It demonstrates how to create and customize these plots using both the MATLAB-style and object-oriented interfaces, along with examples of adding titles, labels, and legends. Additionally, it covers advanced features like visualizing errors and customizing plot legends.

Uploaded by

Padhma Vinodhini
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)
22 views37 pages

Matplotlib Import and Plotting Guide

The document provides a comprehensive guide on using Matplotlib for various types of plots, including line plots, scatter plots, error bars, density and contour plots, and histograms. It demonstrates how to create and customize these plots using both the MATLAB-style and object-oriented interfaces, along with examples of adding titles, labels, and legends. Additionally, it covers advanced features like visualizing errors and customizing plot legends.

Uploaded by

Padhma Vinodhini
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

1/19/25, 8:11 PM Untitled0.

ipynb - Colab

keyboard_arrow_down Importing Matplolib


# Importing necessary libraries
import matplotlib as mpl
import [Link] as plt
import numpy as np

# Setting a style for Matplotlib


[Link]('classic')

# Sample Data
x = [Link](0, 10, 100)
y = [Link](x)

# Creating a simple plot using the MATLAB-style interface


[Link](x, y, label='sin(x)')

# Adding labels and title


[Link]('x axis')
[Link]('y axis')
[Link]('Simple Sin Plot')
[Link]()

# Displaying the plot


[Link]()

# Saving the figure


[Link]('simple_sin_plot.png')

# Using the Object-oriented Interface


fig, ax = [Link]()
[Link](x, y, label='sin(x)', color='blue')

# Adding labels and title with the OO interface


ax.set_xlabel('x axis')
ax.set_ylabel('y axis')
ax.set_title('Simple Sin Plot with OO Interface')
[Link]()

# Displaying the plot


[Link]()

# Saving the figure using OO interface


[Link]('simple_sin_plot_oo.png')

[Link] 1/37
1/19/25, 8:11 PM [Link] - Colab

<Figure size 640x480 with 0 Axes>

keyboard_arrow_down Simple Line Plots


[Link] 2/37
1/19/25, 8:11 PM [Link] - Colab

import [Link] as plt


import numpy as np

# Create a figure and axes


fig, ax = [Link]()

# Generate sample data


x = [Link](0, 10, 100)
y = [Link](x)

# Plot the data


[Link](x, y, label='sin(x)', color='blue', linestyle='-')

# Adjusting the Axes limits


ax.set_xlim(0, 10)
ax.set_ylim(-1.5, 1.5)

# Adding Titles and Labels


ax.set_title('Simple Line Plot of sin(x)')
ax.set_xlabel('x axis')
ax.set_ylabel('y axis')

# Adding a Legend
[Link]()

# Display the plot


[Link]()

# Adjusting and Saving the Figure


[Link]('simple_line_plot.png')

[Link] 3/37
1/19/25, 8:11 PM [Link] - Colab

keyboard_arrow_down Simple Scatter Plots


import [Link] as plt
import numpy as np

# Generate sample data


x = [Link](0, 10, 30)
y = [Link](x)

# Creating Scatter Plots with [Link]


[Link]()
[Link](x, y, 'o', label='Scatter Plot with [Link]') # 'o' is the marker style for ci
[Link]('Scatter Plot with [Link]')
[Link]('x axis')
[Link]('y axis')
[Link]()
[Link]()

# Creating Scatter Plots with [Link]


[Link]()
sizes = 100 * [Link]([Link](x))
colors = y

scatter = [Link](x, y, c=colors, s=sizes, alpha=0.5, cmap='viridis', label='Scatter

[Link] 4/37
1/19/25, 8:11 PM [Link] - Colab

[Link](scatter)
[Link]('Scatter Plot with [Link]')
[Link]('x axis')
[Link]('y axis')
[Link]()
[Link]()

[Link] 5/37
1/19/25, 8:11 PM [Link] - Colab

[Link] 6/37
1/19/25, 8:11 PM [Link] - Colab

keyboard_arrow_down Visualizing Errors


import [Link] as plt
import numpy as np

# Generate sample data


x = [Link](0, 10, 50)
y = [Link](x)

# Adding random noise to the data


y_err = 0.1 + 0.1 * [Link](x)
y_n = y + y_err * [Link](50)

# Creating Error Bars


[Link]()
[Link](x, y, yerr=y_err, fmt='o', ecolor='red', elinewidth=2, capsize=5, label='Err
[Link]('Error Bars Example')
[Link]('x axis')
[Link]('y axis')
[Link]()
[Link]()

# Visualizing Continuous Errors


[Link]()
[Link](x, y_n, 'k.', label='Noisy Data')
[Link](x, y, 'b-', label='Sine Function')

# Use plt.fill_between to visualize continuous error


plt.fill_between(x, y - y_err, y + y_err, color='gray', alpha=0.2)
[Link]('Continuous Error Visualization')
[Link]('x axis')
[Link]('y axis')
[Link]()
[Link]()

[Link] 7/37
1/19/25, 8:11 PM [Link] - Colab

[Link] 8/37
1/19/25, 8:11 PM [Link] - Colab

keyboard_arrow_down Density and Contour Plots


import [Link] as plt
import numpy as np

# Generating sample data


x = [Link](-3, 3, 100)
y = [Link](-3, 3, 100)
X, Y = [Link](x, y)
Z = [Link](X) * [Link](Y)

# Creating a Contour Plot


[Link]()
cs = [Link](X, Y, Z, cmap='RdGy')
[Link](cs)
[Link]('Contour Plot')
[Link]('x axis')
[Link]('y axis')
[Link]()

# Creating a Filled Contour Plot


[Link]()
csf = [Link](X, Y, Z, cmap='RdGy')
[Link](csf)
[Link]('Filled Contour Plot')
[Link]('x axis')
[Link]('y axis')
[Link]()

# Creating an Image Plot using [Link]


[Link]()
[Link](Z, extent=[-3, 3, -3, 3], origin='lower', cmap='RdGy', interpolation='nearest'
[Link]()
[Link]('Image Plot')
[Link]('x axis')
[Link]('y axis')
[Link]()

# Combining Contour and Image Plots


[Link]()
[Link](Z, extent=[-3, 3, -3, 3], origin='lower', cmap='RdGy', alpha=0.5, interpolatio
cs_combined = [Link](X, Y, Z, colors='black')
[Link](cs_combined, inline=1, fontsize=10)
[Link]()
[Link]('Combined Contour and Image Plot')
[Link]('x axis')
[Link]('y axis')
[Link]()

[Link] 9/37
1/19/25, 8:11 PM [Link] - Colab

[Link] 10/37
1/19/25, 8:11 PM [Link] - Colab

[Link] 11/37
1/19/25, 8:11 PM [Link] - Colab

keyboard_arrow_down Histograms, Binnings, and Density


import [Link] as plt
import numpy as np
import seaborn as sns
from [Link] import gaussian_kde

# Generate sample data


data = [Link](1000)

# Creating a simple histogram using [Link]


[Link]()
[Link](data, bins=30, color='blue', edgecolor='black', alpha=0.7)
[Link]('Simple Histogram')
[Link]('Value')
[Link]('Frequency')
[Link]()

# Creating a histogram with stepfilled type


[Link]()
[Link](data, bins=30, density=True, histtype='stepfilled', alpha=0.4, color='green', ed
[Link]('Stepfilled Histogram')
[Link]('Value')
[Link]('Density')
[Link]()

# Two-Dimensional Histograms and Binnings


# Generating multivariate Gaussian data
mean = [0, 0]
cov = [[1, 1], [1, 2]]
x, y = [Link].multivariate_normal(mean, cov, size=1000).T

# Creating a 2D histogram using plt.hist2d


[Link]()
plt.hist2d(x, y, bins=30, cmap='Blues')
[Link](label='Bin Count')
[Link]('2D Histogram')
[Link]('x')
[Link]('y')
[Link]()

# Creating hexbin plot using [Link]


[Link]()
hb = [Link](x, y, gridsize=30, cmap='Purples')
[Link](hb, label='Bin Count')
[Link]('Hexbin Plot')
[Link]('x')
[Link]('y')
[Link]()

# Kernel Density Estimation (KDE)

[Link] 12/37
1/19/25, 8:11 PM [Link] - Colab

# Using [Link].gaussian_kde for KDE


kde = gaussian_kde(data)
x_range = [Link](min(data), max(data), 1000)
[Link]()
[Link](x_range, kde(x_range), color='red')
[Link]('Kernel Density Estimate (KDE)')
[Link]('Value')
[Link]('Density')
[Link]()

# Creating KDE plot using Seaborn


[Link]()
[Link](data, shade=True, color='purple')
[Link]('KDE Plot with Seaborn')
[Link]('Value')
[Link]('Density')
[Link]()

[Link] 13/37
1/19/25, 8:11 PM [Link] - Colab

[Link] 14/37
1/19/25, 8:11 PM [Link] - Colab

[Link] 15/37
1/19/25, 8:11 PM [Link] - Colab

<ipython-input-8-89080f3c700d>:62: FutureWarning:

`shade` is now deprecated in favor of `fill`; setting `fill=True`.


This will become an error in seaborn v0.14.0; please update your code.

[Link](data, shade=True, color='purple')

[Link] 16/37
1/19/25, 8:11 PM [Link] - Colab

keyboard_arrow_down Customizing Plot Legends in Matplotlib


import [Link] as plt
import numpy as np

# Generating sample data


x = [Link](0, 10, 100)
y1 = [Link](x)
y2 = [Link](x)

# Basic Legend Creation


[Link]()
[Link](x, y1, label='sin(x)')
[Link](x, y2, label='cos(x)')
[Link](loc='best')
[Link]('Basic Legend')
[Link]('x axis')
[Link]('y axis')
[Link]()

# Advanced Customization
[Link]()
[Link](x, y1, label='sin(x)')
[Link](x, y2, label='cos(x)')
[Link](loc='upper right', frameon=True, fancybox=True, shadow=True, framealpha=0.5, b
[Link]('Advanced Customization')
[Link]('x axis')
[Link]('y axis')
[Link]()

# Choosing Legend Elements


fig, ax = [Link]()
line1, = [Link](x, y1, label='sin(x)')
line2, = [Link](x, y2, label='cos(x)')
[Link](handles=[line1, line2], loc='upper left', ncol=2)
[Link]('Choosing Legend Elements')
[Link]('x axis')
[Link]('y axis')
[Link]()

# Legend for Size of Points


[Link]()
sizes = 100 * [Link](x)**2
scatter = [Link](x, y1, s=sizes, label='Data Points')
handles, labels = scatter.legend_elements(prop='sizes', num=4, alpha=0.6)
[Link](handles, labels, title='Size')
[Link]('Legend for Size of Points')
[Link]('x axis')
[Link]('y axis')
[Link]()

# Multiple Legends
[Link] 17/37
1/19/25, 8:11 PM [Link] - Colab

fig, ax = [Link]()
line1, = [Link](x, y1, label='sin(x)')
line2, = [Link](x, y2, label='cos(x)')
first_legend = [Link](handles=[line1, line2], loc='upper left')

# Adding a second legend with a different location


line3 = plt.Line2D([], [], color='red', marker='o', linestyle='None', markersize=10, labe
second_legend = [Link](handles=[line3], loc='upper right')
ax.add_artist(first_legend)
ax.add_artist(second_legend)
[Link]('Multiple Legends')
[Link]('x axis')
[Link]('y axis')
[Link]()

[Link] 18/37
1/19/25, 8:11 PM [Link] - Colab

[Link] 19/37
1/19/25, 8:11 PM [Link] - Colab

[Link] 20/37
1/19/25, 8:11 PM [Link] - Colab

[Link] 21/37
1/19/25, 8:11 PM [Link] - Colab

keyboard_arrow_down Customizing Colorbars


import [Link] as plt
import numpy as np
from [Link] import load_digits
from [Link] import Isomap

# Generating sample data


[Link](0)
x = [Link](1000)
y = [Link](1000)

# Creating a scatter plot with color mapping


[Link]()
[Link](x, y, c=[Link](x**2 + y**2), cmap='viridis')
[Link](label='Color Bar')
[Link]('Scatter Plot with Color Bar')
[Link]('x axis')
[Link]('y axis')
[Link]()

# Creating a discrete colorbar


[Link]()
cmap = [Link].get_cmap('viridis', 10)
sc = [Link](x, y, c=[Link](x**2 + y**2), cmap=cmap)
[Link](sc, ticks=[Link](0, [Link]([Link](x**2 + y**2)), 10))
[Link]('Scatter Plot with Discrete Color Bar')
[Link]('x axis')
[Link]('y axis')
[Link]()

# Loading and visualizing the digits dataset


digits = load_digits()
X = [Link]
y = [Link]

# Projecting the digits dataset into 2D using Isomap


iso = Isomap(n_components=2)
iso_proj = iso.fit_transform(X)

# Creating a scatter plot of the Isomap projection with digit labels


[Link]()
scatter = [Link](iso_proj[:, 0], iso_proj[:, 1], c=y, cmap='Spectral', alpha=0.7)
[Link](scatter, label='Digit Label')
[Link]('Isomap Projection of Digits Dataset')
[Link]('Component 1')
[Link]('Component 2')
[Link]()

[Link] 22/37
1/19/25, 8:11 PM [Link] - Colab

<ipython-input-6-8c99b090878e>:22: MatplotlibDeprecationWarning: The get_cmap functio


cmap = [Link].get_cmap('viridis', 10)

/usr/local/lib/python3.11/dist-packages/sklearn/manifold/_isomap.py:384: UserWarning:
self fit transform(X)
[Link] 23/37
1/19/25, 8:11 PM [Link] - Colab
self._fit_transform(X)
/usr/local/lib/python3.11/dist-packages/scipy/sparse/_index.py:108: SparseEfficiencyW
self._set_intXint(row, col, [Link][0])

[Link] 24/37
1/19/25, 8:11 PM [Link] - Colab

keyboard_arrow_down Multiple Subplots


import [Link] as plt
import numpy as np

# Generate sample data


x = [Link](0, 10, 100)
y1 = [Link](x)
y2 = [Link](x)

# [Link]: Creating Subplots by Hand


fig = [Link]()
ax1 = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # Main axes
ax2 = fig.add_axes([0.65, 0.65, 0.2, 0.2]) # Inset axes

[Link](x, y1, 'b-')


ax1.set_title('Main Plot')

[Link](x, y2, 'r-')


ax2.set_title('Inset Plot')
[Link]()

# [Link]: Simple Grids of Subplots


[Link]()
for i in range(1, 5):
[Link](2, 2, i) # 2x2 grid, current subplot
[Link](x, [Link](x + i)) # Different sinusoidal function
[Link](f'Subplot {i}')
plt.tight_layout()
[Link]()

# [Link]: The Whole Grid in One Go


fig, axs = [Link](2, 3, sharex=True, sharey=True)
for i, ax in enumerate([Link]):
[Link](x, [Link](x + i))
ax.set_title(f'Subplot {i+1}')
fig.tight_layout()
[Link]()

# [Link]: More Complicated Arrangements


import [Link] as gridspec

fig = [Link]()
gs = [Link](3, 3)

ax1 = fig.add_subplot(gs[0, 0])


ax2 = fig.add_subplot(gs[0, 1:3])
ax3 = fig.add_subplot(gs[1:, 0])
ax4 = fig.add_subplot(gs[1:, 1:3])

[Link](x, y1)

[Link] 25/37
1/19/25, 8:11 PM [Link] - Colab

ax1.set_title('Ax1')

[Link](x, y2)
ax2.set_title('Ax2')

[Link](x, -y2)
ax3.set_title('Ax3')

[Link](x, -y1)
ax4.set_title('Ax4')

plt.tight_layout()
[Link]()

[Link] 26/37
1/19/25, 8:11 PM [Link] - Colab

[Link] 27/37
1/19/25, 8:11 PM [Link] - Colab

[Link] 28/37
1/19/25, 8:11 PM [Link] - Colab

keyboard_arrow_down Customizing Ticks


import [Link] as plt
import numpy as np

# Generate sample data


x = [Link](0, 10, 100)
y = [Link](x)

# Basic plot setup


fig, ax = [Link]()
[Link](x, y)

# Customizing major and minor ticks


[Link].set_major_locator([Link](2))
[Link].set_minor_locator([Link](0.5))
[Link].set_major_locator([Link](5))
[Link].set_minor_locator([Link](0.5))

# Adding gridlines for better visibility


[Link](which='both', linestyle='--', linewidth=0.5)

# Hiding ticks or labels


[Link].set_major_formatter([Link]())
[Link].set_minor_locator([Link]())
[Link].set_minor_formatter([Link]())

# Using [Link] for custom tick labels


def format_func(value, tick_number):
return f'{value:.1f} π'
[Link].set_major_formatter([Link](format_func))

# Labels and title


ax.set_xlabel('x axis')
ax.set_ylabel('y axis')
ax.set_title('Customizing Ticks Example')

[Link]()

[Link] 29/37
1/19/25, 8:11 PM [Link] - Colab

keyboard_arrow_down Customizing Matplotlib: Configurations and Stylesheets


import [Link] as plt
import numpy as np

# Generate sample data


x = [Link](0, 10, 100)
y1 = [Link](x)
y2 = [Link](x)

# Plot Customization by Hand


[Link]()
[Link](x, y1, label='sin(x)')
[Link](x, y2, label='cos(x)')
[Link](color='white', linestyle='-', linewidth=1.5)
[Link]().patch.set_facecolor('gray')
[Link]().spines['top'].set_visible(False)
[Link]().spines['right'].set_visible(False)
plt.tick_params(direction='inout', color='white')
[Link]('Customized Plot by Hand')
[Link]('x axis')
[Link]('y axis')
[Link]()
[Link]()

[Link] 30/37
1/19/25, 8:11 PM [Link] - Colab

# Changing Defaults: rcParams


[Link]('figure', facecolor='lightgray')
[Link]('axes', facecolor='gray', edgecolor='white', grid=True, axisbelow=True)
[Link]('grid', color='white', linestyle='-', linewidth=1)
[Link]('xtick', direction='out', color='white')
[Link]('ytick', direction='out', color='white')
[Link]('patch', edgecolor='none')

# Applying rcParams settings to a plot


[Link]()
[Link](x, y1, label='sin(x)')
[Link](x, y2, label='cos(x)')
[Link]('Plot with Customized rcParams')
[Link]('x axis')
[Link]('y axis')
[Link]()
[Link]()

# List available stylesheets


print([Link])

# Applying Built-in Stylesheets


[Link]('fivethirtyeight')
[Link]()
[Link](x, y1, label='sin(x)')
[Link](x, y2, label='cos(x)')
[Link]('Plot with FiveThirtyEight Style')
[Link]('x axis')
[Link]('y axis')
[Link]()
[Link]()

# Temporarily Applying a Style


with [Link]('ggplot'):
[Link]()
[Link](x, y1, label='sin(x)')
[Link](x, y2, label='cos(x)')
[Link]('Plot with ggplot Style (Temporary)')
[Link]('x axis')
[Link]('y axis')
[Link]()
[Link]()

[Link] 31/37
1/19/25, 8:11 PM [Link] - Colab

['Solarize_Light2', '_classic_test_patch', '_mpl-gallery', '_mpl-gallery-nogrid', 'bm

[Link] 32/37
1/19/25, 8:11 PM [Link] - Colab

[Link] 33/37
1/19/25, 8:11 PM [Link] - Colab

keyboard_arrow_down Three-Dimensional Plotting in Matplotlib


import [Link] as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D

# Generate sample data


theta = [Link](-4 * [Link], 4 * [Link], 100)
z = [Link](-2, 2, 100)
r = z**2 + 1
x = r * [Link](theta)
y = r * [Link](theta)

# Three-Dimensional Points and Lines


fig = [Link]()
ax = fig.add_subplot(111, projection='3d')
ax.plot3D(x, y, z, 'gray')
ax.scatter3D(x, y, z, c=z, cmap='Greens')
[Link]('3D Points and Lines')
[Link]()

# Three-Dimensional Contour Plots


X, Y = [Link]([Link](-5, 5, 50), [Link](-5, 5, 50))
Z = [Link]([Link](X**2 + Y**2))

fig = [Link]()
ax = fig.add_subplot(111, projection='3d')
ax.contour3D(X, Y, Z, 50, cmap='binary')
ax.view_init(elev=45, azim=120)
[Link]('3D Contour Plot')
[Link]()

# Wireframes and Surface Plots


fig = [Link]()
ax = fig.add_subplot(111, projection='3d')
ax.plot_wireframe(X, Y, Z, color='black')
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='viridis', edgecolor='none')
[Link]('3D Wireframe and Surface Plot')
[Link]()

# Surface Triangulations
fig = [Link]()
ax = fig.add_subplot(111, projection='3d')

# Generate a Mobius strip


theta = [Link](0, 2 * [Link], 30)
w = [Link](-1, 1, 15)
theta, w = [Link](theta, w)
R = 1
x = (R + w * [Link](theta / 2)) * [Link](theta)
y = (R + w * [Link](theta / 2)) * [Link](theta)
z = w * [Link](theta / 2)
[Link] 34/37
1/19/25, 8:11 PM [Link] - Colab

ax.plot_trisurf([Link](), [Link](), [Link](), cmap='viridis')


[Link]('Mobius Strip')
[Link]()

[Link] 35/37
1/19/25, 8:11 PM [Link] - Colab

[Link] 36/37
1/19/25, 8:11 PM [Link] - Colab

[Link] 37/37

You might also like