Embark on a journey of knowledge! Take the quiz and earn valuable credits.
Take A QuizChallenge yourself and boost your learning! Start the quiz now to earn credits.
Take A QuizUnlock your potential! Begin the quiz, answer questions, and accumulate credits along the way.
Take A Quiz
🔹 1. Introduction
In this chapter, we will explore how to create 3D plots
and other specialized visualizations using Matplotlib. 3D plots are
essential when working with data that has three dimensions or more. Matplotlib
provides support for 3D plotting using the Axes3D module, which can
create 3D scatter plots, surface plots, contour plots, and
more.
In addition to 3D plots, we will also cover some other specialized
visualizations that can help you present complex data, such as polar
plots, heatmaps, and violin plots.
By the end of this chapter, you will be able to:
🔹 2. Creating 3D Plots in
Matplotlib
Matplotlib provides the Axes3D class for creating 3D plots.
These plots are useful for visualizing relationships between three variables,
such as 3D scatter plots or surface plots.
✅ Creating a 3D Scatter Plot
A 3D scatter plot allows you to visualize the relationship
between three continuous variables by displaying data points in a
three-dimensional space.
from
mpl_toolkits.mplot3d import Axes3D
import
matplotlib.pyplot as plt
import
numpy as np
#
Generate 3D data
x
= np.linspace(-5, 5, 100)
y
= np.linspace(-5, 5, 100)
z
= np.sin(np.sqrt(x**2 + y**2))
#
Create a 3D plot
fig
= plt.figure()
ax
= fig.add_subplot(111, projection='3d')
#
Scatter plot
ax.scatter(x,
y, z, color='r')
#
Set labels
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
plt.show()
In this example:
✅ Creating a 3D Surface Plot
A 3D surface plot is useful for visualizing a 3D
surface formed by the relationship between three variables.
#
Create a 3D surface plot
fig
= plt.figure()
ax
= fig.add_subplot(111, projection='3d')
#
Surface plot
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))
ax.plot_surface(X,
Y, Z, cmap='viridis')
#
Set labels
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
plt.show()
Here:
🔹 3. Creating Contour
Plots in 3D
A contour plot displays level curves of a 3D surface,
showing the values of a function on a 2D plane.
✅ Creating a 3D Contour Plot
#
Create a 3D contour plot
fig
= plt.figure()
ax
= fig.add_subplot(111, projection='3d')
#
Contour plot
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))
ax.contour3D(X,
Y, Z, 50, cmap='inferno')
#
Set labels
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
plt.show()
🔹 4. Polar Plots
Polar plots are used for visualizing data in polar
coordinates (angles and radii), which is useful when analyzing data related
to circular motion or periodic functions.
✅ Creating a Basic Polar Plot
#
Data for plotting
angles
= np.linspace(0, 2 * np.pi, 100)
radii
= np.sin(angles) # Radius based on sine
function
#
Create a polar plot
fig
= plt.figure()
ax
= fig.add_subplot(111, projection='polar')
ax.plot(angles,
radii)
plt.title('Polar
Plot of Sine Function')
plt.show()
In this example:
🔹 5. Heatmaps
Heatmaps are used to represent matrix-like data
visually, where the values are represented by colors.
✅ Creating a Heatmap
Heatmaps are especially useful for visualizing correlations
or the density of values across a 2D grid.
#
Create a 2D data matrix for the heatmap
data
= np.random.rand(10, 10)
#
Create a heatmap
plt.imshow(data,
cmap='hot', interpolation='nearest')
plt.colorbar() # Add a color bar
plt.title('Heatmap
Example')
plt.show()
In this example:
🔹 6. Violin Plots
Violin plots are used to display the distribution of data,
similar to a box plot, but with a rotated kernel density plot.
✅ Creating a Violin Plot
import
seaborn as sns
#
Create sample data
data
= np.random.normal(0, 1, 100)
#
Create a violin plot
sns.violinplot(data=data)
plt.title('Violin
Plot')
plt.show()
🔹 7. Summary Table
Plot Type |
Function/Method |
Description |
3D Scatter
Plot |
ax.scatter() |
Visualize
individual data points in 3D space |
3D Surface
Plot |
ax.plot_surface() |
Plot a
surface defined by a function in 3D |
3D Contour
Plot |
ax.contour3D() |
Create
contour lines for a 3D surface |
Polar Plot |
ax.plot()
with projection='polar' |
Visualize
data in polar coordinates |
Heatmap |
plt.imshow() |
Display
matrix data using color intensities |
Violin Plot |
sns.violinplot() |
Display the
distribution of data using density plots |
Matplotlib is a powerful Python library used for creating static, animated, and interactive visualizations. It provides extensive control over plot design and is used by data scientists and analysts for visualizing data.
pip install matplotlib
Some of the most common plot types include line plots, bar charts, scatter plots, histograms, and pie charts.
Matplotlib offers various customization options, including color, line style, markers, axis labels, titles, and more. You can use functions like plt.plot(), plt.title(), plt.xlabel(), and plt.ylabel() to modify the style.
plt.savefig('plot.png')
plt.show() displays the plot on the screen, while plt.savefig() saves the plot as an image file (e.g., PNG, JPEG, SVG, PDF).
Yes, Matplotlib supports interactive features, such as zooming, panning, and hovering over elements. For even more advanced interactivity, you can combine Matplotlib with libraries like Plotly or Bokeh.
sizes = [10, 20, 30, 40]
labels = ['A', 'B', 'C', 'D']
plt.pie(sizes, labels=labels)
plt.show()
Yes, Matplotlib supports 3D plotting via the Axes3D module. You can create 3D scatter plots, surface plots, and more
plt.figure(figsize=(10, 6)) # Set figure size to 10x6 inches
Please log in to access this content. You will be redirected to the login page shortly.
LoginReady to take your education and career to the next level? Register today and join our growing community of learners and professionals.
Comments(0)