CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-matplotlib

Comprehensive Python library for creating static, animated, and interactive visualizations

Pending
Overview
Eval results
Files

3d-plotting.mddocs/

3D Plotting

Three-dimensional visualization capabilities through the mplot3d toolkit. Matplotlib provides comprehensive 3D plotting functionality including line plots, surface plots, scatter plots, wireframes, and volume rendering.

Capabilities

3D Axes

Enhanced axes class with 3D coordinate system support.

from mpl_toolkits.mplot3d import Axes3D
import mpl_toolkits.mplot3d.axes3d as axes3d

class Axes3D:
    def __init__(self, fig, rect=None, *args, azim=-60, elev=30, zscale=None,
                sharez=None, proj_type='persp', box_aspect=None, **kwargs):
        """3D axes with perspective projection."""
    
    # 3D plotting methods
    def plot(self, xs, ys, zs=0, *args, zdir='z', **kwargs) -> Line3D:
        """Plot lines and/or markers in 3D."""
    
    def scatter(self, xs, ys, zs=0, c=None, s=20, depthshade=True, *args,
               zdir='z', **kwargs) -> Path3DCollection:
        """Create a 3D scatter plot."""
    
    def bar(self, left, height, zs=0, zdir='z', *args, **kwargs) -> Poly3DCollection:
        """Create a 3D bar plot."""
    
    def bar3d(self, x, y, z, dx, dy, dz, color=None, zsort='average',
             shade=True, lightsource=None, *args, **kwargs) -> Poly3DCollection:
        """Create a 3D bar plot with rectangular bars."""
    
    # Surface and mesh plotting
    def plot_surface(self, X, Y, Z, *args, norm=None, vmin=None, vmax=None,
                    lightsource=None, **kwargs) -> Poly3DCollection:
        """Create a 3D surface plot."""
    
    def plot_wireframe(self, X, Y, Z, *args, rstride=1, cstride=1, **kwargs) -> Line3DCollection:
        """Create a 3D wireframe plot."""
    
    def plot_trisurf(self, *args, color=None, norm=None, vmin=None, vmax=None,
                    lightsource=None, **kwargs) -> Poly3DCollection:
        """Create a 3D surface plot from triangulated data."""
    
    # Contour plotting
    def contour(self, X, Y, Z, *args, extend3d=False, stride=5, zdir='z',
               offset=None, **kwargs) -> Path3DCollection:
        """Create 3D contour lines."""
    
    def contourf(self, X, Y, Z, *args, zdir='z', offset=None, **kwargs) -> Path3DCollection:
        """Create filled 3D contours."""
    
    # Text and annotation
    def text(self, x, y, z, s, zdir=None, **kwargs) -> Text3D:
        """Add text in 3D space."""
    
    def text2D(self, x, y, s, fontdict=None, **kwargs) -> Text:
        """Add 2D text to 3D axes."""
    
    # Axis and view control
    def set_xlim(self, left=None, right=None, *, emit=True, auto=False) -> tuple:
        """Set x-axis limits."""
    
    def set_ylim(self, bottom=None, top=None, *, emit=True, auto=False) -> tuple:
        """Set y-axis limits."""
    
    def set_zlim(self, bottom=None, top=None, *, emit=True, auto=False) -> tuple:
        """Set z-axis limits."""
    
    def set_xlabel(self, xlabel, fontdict=None, labelpad=None, **kwargs) -> Text:
        """Set x-axis label."""
    
    def set_ylabel(self, ylabel, fontdict=None, labelpad=None, **kwargs) -> Text:
        """Set y-axis label."""
    
    def set_zlabel(self, zlabel, fontdict=None, labelpad=None, **kwargs) -> Text:
        """Set z-axis label."""
    
    def view_init(self, elev=None, azim=None, roll=None) -> None:
        """Set the elevation and azimuth of the axes."""
    
    def set_proj_type(self, proj_type, focal_length=None) -> None:
        """Set the projection type ('persp' or 'ortho')."""
    
    def set_box_aspect(self, aspect, *, zoom=1) -> None:
        """Set the aspect ratio of the 3D plot box."""

3D Collections and Artists

Specialized collection classes for 3D rendering.

from mpl_toolkits.mplot3d.art3d import *

class Line3D:
    def __init__(self, xs, ys, zs, *args, **kwargs):
        """3D line object."""
    
    def set_data_3d(self, xs, ys, zs) -> None:
        """Set 3D line data."""

class Line3DCollection:
    def __init__(self, segments, *args, **kwargs):
        """Collection of 3D line segments."""
    
    def set_segments(self, segments) -> None:
        """Set line segments."""

class Poly3DCollection:
    def __init__(self, verts, *args, zsort='average', **kwargs):
        """Collection of 3D polygons."""
    
    def set_verts(self, verts) -> None:
        """Set polygon vertices."""
    
    def set_zsort(self, zsort) -> None:
        """Set z-sorting method."""

class Path3DCollection:
    def __init__(self, paths, *args, zs=0, zdir='z', depthshade=True, **kwargs):
        """Collection of 3D paths."""
    
    def set_3d_properties(self, zs=0, zdir='z') -> None:
        """Set 3D properties."""

class Text3D:
    def __init__(self, x=0, y=0, z=0, text='', zdir='z', **kwargs):
        """3D text object."""
    
    def set_position_3d(self, xyz, zdir=None) -> None:
        """Set 3D text position."""

Utility Functions

Helper functions for 3D plotting setup and data generation.

from mpl_toolkits.mplot3d import proj3d

def persp_transformation(xvals, yvals, zvals, M) -> tuple:
    """Apply perspective transformation to 3D coordinates."""

def orthogonal_proj(zfront, zback) -> np.ndarray:
    """Return orthographic projection matrix."""

def world_transformation(xmin, xmax, ymin, ymax, zmin, zmax,
                        pb_aspect) -> np.ndarray:
    """Return world transformation matrix."""

# Axis creation helper
def Axes3D(fig=None, rect=None, *args, **kwargs):
    """Create a 3D axes in the given figure."""

Usage Examples

Basic 3D Line Plot

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np

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

# Generate 3D line data
t = np.linspace(0, 4*np.pi, 100)
x = np.sin(t)
y = np.cos(t)
z = t

# Plot 3D line
ax.plot(x, y, z, 'b-', linewidth=2, label='3D Spiral')

# Customize axes
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
ax.set_title('3D Line Plot')
ax.legend()

plt.show()

3D Scatter Plot

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np

fig = plt.figure(figsize=(12, 5))

# First subplot: Basic scatter
ax1 = fig.add_subplot(121, projection='3d')

# Generate random 3D points
n = 100
x = np.random.standard_normal(n)
y = np.random.standard_normal(n)
z = np.random.standard_normal(n)
colors = np.random.rand(n)
sizes = 1000 * np.random.rand(n)

ax1.scatter(x, y, z, c=colors, s=sizes, alpha=0.6, cmap='viridis')
ax1.set_xlabel('X')
ax1.set_ylabel('Y')
ax1.set_zlabel('Z')
ax1.set_title('3D Scatter Plot')

# Second subplot: Clustered data
ax2 = fig.add_subplot(122, projection='3d')

# Generate clustered data
n_clusters = 3
n_points = 50

for i in range(n_clusters):
    # Random cluster center
    center = np.random.rand(3) * 10
    
    # Generate points around center
    x_cluster = center[0] + np.random.normal(0, 1, n_points)
    y_cluster = center[1] + np.random.normal(0, 1, n_points)
    z_cluster = center[2] + np.random.normal(0, 1, n_points)
    
    ax2.scatter(x_cluster, y_cluster, z_cluster, s=60, alpha=0.8,
               label=f'Cluster {i+1}')

ax2.set_xlabel('X')
ax2.set_ylabel('Y')
ax2.set_zlabel('Z')
ax2.set_title('Clustered 3D Data')
ax2.legend()

plt.tight_layout()
plt.show()

3D Surface Plot

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np

fig = plt.figure(figsize=(15, 5))

# Create mesh grid
x = np.linspace(-5, 5, 50)
y = np.linspace(-5, 5, 50)
X, Y = np.meshgrid(x, y)

# First surface: Gaussian
ax1 = fig.add_subplot(131, projection='3d')
Z1 = np.exp(-(X**2 + Y**2) / 10)
surf1 = ax1.plot_surface(X, Y, Z1, cmap='viridis', alpha=0.8)
ax1.set_title('Gaussian Surface')
ax1.set_xlabel('X')
ax1.set_ylabel('Y')
ax1.set_zlabel('Z')
fig.colorbar(surf1, ax=ax1, shrink=0.5)

# Second surface: Ripple effect
ax2 = fig.add_subplot(132, projection='3d')
R = np.sqrt(X**2 + Y**2)
Z2 = np.sin(R) / (R + 0.1)  # Add small value to avoid division by zero
surf2 = ax2.plot_surface(X, Y, Z2, cmap='plasma', alpha=0.8)
ax2.set_title('Ripple Surface')
ax2.set_xlabel('X')
ax2.set_ylabel('Y')
ax2.set_zlabel('Z')
fig.colorbar(surf2, ax=ax2, shrink=0.5)

# Third surface: Saddle
ax3 = fig.add_subplot(133, projection='3d')
Z3 = X**2 - Y**2
surf3 = ax3.plot_surface(X, Y, Z3, cmap='coolwarm', alpha=0.8)
ax3.set_title('Saddle Surface')
ax3.set_xlabel('X')
ax3.set_ylabel('Y')
ax3.set_zlabel('Z')
fig.colorbar(surf3, ax=ax3, shrink=0.5)

plt.tight_layout()
plt.show()

3D Wireframe and Contour

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np

fig = plt.figure(figsize=(15, 10))

# Create data
x = np.linspace(-3, 3, 30)
y = np.linspace(-3, 3, 30)
X, Y = np.meshgrid(x, y)
Z = np.sin(np.sqrt(X**2 + Y**2))

# Wireframe plot
ax1 = fig.add_subplot(221, projection='3d')
ax1.plot_wireframe(X, Y, Z, color='blue', alpha=0.7)
ax1.set_title('3D Wireframe')
ax1.set_xlabel('X')
ax1.set_ylabel('Y')
ax1.set_zlabel('Z')

# Surface with wireframe overlay
ax2 = fig.add_subplot(222, projection='3d')
ax2.plot_surface(X, Y, Z, cmap='viridis', alpha=0.6)
ax2.plot_wireframe(X, Y, Z, color='black', alpha=0.3, linewidth=0.5)
ax2.set_title('Surface + Wireframe')
ax2.set_xlabel('X')
ax2.set_ylabel('Y')
ax2.set_zlabel('Z')

# 3D contour lines
ax3 = fig.add_subplot(223, projection='3d')
ax3.contour(X, Y, Z, levels=15, cmap='viridis')
ax3.set_title('3D Contour Lines')
ax3.set_xlabel('X')
ax3.set_ylabel('Y')
ax3.set_zlabel('Z')

# 3D filled contours
ax4 = fig.add_subplot(224, projection='3d')
ax4.contourf(X, Y, Z, levels=15, cmap='plasma', alpha=0.8)
ax4.set_title('3D Filled Contours')
ax4.set_xlabel('X')
ax4.set_ylabel('Y')
ax4.set_zlabel('Z')

plt.tight_layout()
plt.show()

3D Bar Plot

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np

fig = plt.figure(figsize=(12, 8))
ax = fig.add_subplot(111, projection='3d')

# Create 3D bar chart data
xpos = np.arange(5)
ypos = np.arange(4)
xpos, ypos = np.meshgrid(xpos, ypos)

xpos = xpos.ravel()
ypos = ypos.ravel()
zpos = np.zeros_like(xpos)

# Bar dimensions
dx = dy = 0.8
dz = np.random.rand(len(xpos)) * 10

# Color each bar based on its height
colors = plt.cm.viridis(dz / float(dz.max()))

# Create 3D bars
bars = ax.bar3d(xpos, ypos, zpos, dx, dy, dz, color=colors, alpha=0.8)

# Customize plot
ax.set_xlabel('X Position')
ax.set_ylabel('Y Position')
ax.set_zlabel('Height')
ax.set_title('3D Bar Chart')

# Add colorbar
mappable = plt.cm.ScalarMappable(cmap='viridis')
mappable.set_array(dz)
fig.colorbar(mappable, ax=ax, shrink=0.5, aspect=20)

plt.show()

Interactive 3D Plot with View Control

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np

# Create parametric surface
u = np.linspace(0, 2 * np.pi, 50)
v = np.linspace(0, np.pi, 50)
U, V = np.meshgrid(u, v)

# Torus surface
R = 3  # Major radius
r = 1  # Minor radius
X = (R + r * np.cos(V)) * np.cos(U)
Y = (R + r * np.cos(V)) * np.sin(U)
Z = r * np.sin(V)

fig = plt.figure(figsize=(12, 9))

# Create multiple views
views = [(30, 45), (60, 30), (0, 0), (90, 90)]
titles = ['Default View', 'Side View', 'Front View', 'Top View']

for i, (elev, azim) in enumerate(views):
    ax = fig.add_subplot(2, 2, i+1, projection='3d')
    
    # Plot torus
    surf = ax.plot_surface(X, Y, Z, cmap='plasma', alpha=0.8)
    
    # Set view angle
    ax.view_init(elev=elev, azim=azim)
    
    # Customize
    ax.set_xlabel('X')
    ax.set_ylabel('Y')
    ax.set_zlabel('Z')
    ax.set_title(f'{titles[i]} (elev={elev}°, azim={azim}°)')
    
    # Equal aspect ratio
    ax.set_box_aspect([1,1,0.5])

plt.tight_layout()
plt.show()

# Create interactive plot
fig_interactive = plt.figure(figsize=(10, 8))
ax_interactive = fig_interactive.add_subplot(111, projection='3d')

surf = ax_interactive.plot_surface(X, Y, Z, cmap='plasma', alpha=0.8)
ax_interactive.set_xlabel('X')
ax_interactive.set_ylabel('Y')
ax_interactive.set_zlabel('Z')
ax_interactive.set_title('Interactive 3D Torus (drag to rotate)')

# Add colorbar
fig_interactive.colorbar(surf, shrink=0.5, aspect=20)

plt.show()

Advanced 3D Visualization

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np

# Create complex 3D scene
fig = plt.figure(figsize=(14, 10))
ax = fig.add_subplot(111, projection='3d')

# Generate multiple surfaces
x = np.linspace(-5, 5, 30)
y = np.linspace(-5, 5, 30)
X, Y = np.meshgrid(x, y)

# Bottom surface (terrain-like)
Z1 = 2 * np.sin(np.sqrt(X**2 + Y**2)) * np.exp(-0.1 * np.sqrt(X**2 + Y**2))
surf1 = ax.plot_surface(X, Y, Z1, cmap='terrain', alpha=0.8)

# Top surface (canopy-like)
Z2 = Z1 + 3 + np.cos(X) * np.cos(Y)
surf2 = ax.plot_wireframe(X, Y, Z2, color='green', alpha=0.6, linewidth=0.5)

# Add some 3D scatter points (trees)
n_trees = 20
tree_x = np.random.uniform(-4, 4, n_trees)
tree_y = np.random.uniform(-4, 4, n_trees)
tree_z = np.interp(np.sqrt(tree_x**2 + tree_y**2), 
                  np.sqrt(X[0,:]**2 + Y[:,0]**2), Z1[0,:])

ax.scatter(tree_x, tree_y, tree_z, c='brown', s=100, marker='^', 
          label='Trees', alpha=0.8)

# Add 3D text labels
ax.text(0, 0, 6, 'Peak', fontsize=12, weight='bold')
ax.text(-4, -4, -2, 'Valley', fontsize=10)

# Customize the plot
ax.set_xlabel('X Distance')
ax.set_ylabel('Y Distance')
ax.set_zlabel('Height')
ax.set_title('3D Landscape Visualization')
ax.legend()

# Set viewing angle for best perspective
ax.view_init(elev=20, azim=45)

# Add colorbar
fig.colorbar(surf1, ax=ax, shrink=0.5, aspect=20, label='Elevation')

plt.tight_layout()
plt.show()

Install with Tessl CLI

npx tessl i tessl/pypi-matplotlib

docs

3d-plotting.md

animation.md

backends.md

colors-styling.md

index.md

object-oriented.md

pyplot.md

shapes.md

tile.json