DEV Community

Rajasekaran Palraj
Rajasekaran Palraj

Posted on

Data Analysis - Matplot Lib - Notes

Matplotlib is a powerful and versatile open-source plotting library for Python, designed to help users visualize data in a variety of formats. Developed by John D. Hunter in 2003, it enables users to graphically represent data, facilitating easier analysis and understanding. If you want to convert your boring data into interactive plots and graphs, Matplotlib is the tool for you.

Components or Parts of Matplotlib Figure
Anatomy of a Matplotlib Plot: This section dives into the key components of a Matplotlib plot, including figures, axes, titles, and legends, essential for effective data visualization.

The parts of a Matplotlib figure include (as shown in the figure above):

Figure: The overarching container that holds all plot elements, acting as the canvas for visualizations.
Axes: The areas within the figure where data is plotted; each figure can contain multiple axes.
Axis: Represents the x-axis and y-axis, defining limits, tick locations, and labels for data interpretation.
Lines and Markers: Lines connect data points to show trends, while markers denote individual data points in plots like scatter plots.
Title and Labels: The title provides context for the plot, while axis labels describe what data is being represented on each axis.

Matplotlib Pyplot
Pyplot is a module within Matplotlib that provides a MATLAB-like interface for making plots. It simplifies the process of adding plot elements such as lines, images, and text to the axes of the current figure. Steps to Use Pyplot:

Import Matplotlib: Start by importing matplotlib.pyplot as plt.
Create Data: Prepare your data in the form of lists or arrays.
Plot Data: Use plt.plot() to create the plot.
Customize Plot: Add titles, labels, and other elements using methods like plt.title(), plt.xlabel(), and plt.ylabel().
Display Plot: Use plt.show() to display the plot.
Let's visualize a basic plot, and understand basic components of matplotlib figure:

import matplotlib.pyplot as plt

x = [0, 2, 4, 6, 8]
y = [0, 4, 16, 36, 64]

fig, ax = plt.subplots()

ax.plot(x, y, marker='o', label="Data Points")

ax.set_title("Basic Components of Matplotlib Figure")
ax.set_xlabel("X-Axis")
ax.set_ylabel("Y-Axis")



plt.show()
Output:

Basic Components of matplotlib figure
Different Types of Plots in Matplotlib
Matplotlib offers a wide range of plot types to suit various data visualization needs. Here are some of the most commonly used types of plots in Matplotlib:

  1. Line Graph
  2. Bar Chart
  3. Histogram
  4. Scatter Plot
  5. Pie Chart
  6. 3D Plot and many more..

Bar chart and Pie chart
For learning about the different types of plots in Matplotlib, please read Types of Plots in Matplotlib.

Key Features of Matplotlib
Versatile Plotting: Create a wide variety of visualizations, including line plots, scatter plots, bar charts, and histograms.
Extensive Customization: Control every aspect of your plots, from colors and markers to labels and annotations.
Seamless Integration with NumPy: Effortlessly plot data arrays directly, enhancing data manipulation capabilities.
High-Quality Graphics: Generate publication-ready plots with precise control over aesthetics.
Cross-Platform Compatibility: Use Matplotlib on Windows, macOS, and Linux without issues.
Interactive Visualizations: Engage with your data dynamically through interactive plotting features.

Matplotlib Simple Line Plot

import matplotlib.pyplot as plt
import numpy as np

x = np.array([1, 2, 3, 4])  # X-axis 
y = x*2  # Y-axis

plt.plot(x, y)  
plt.show()
Enter fullscreen mode Exit fullscreen mode
import matplotlib.pyplot as plt
import numpy as np

x = np.array([1, 2, 3, 4])
y = x*2

plt.plot(x, y)
plt.xlabel("X-axis")        # Label for the X-axis
plt.ylabel("Y-axis")        # Label for the Y-axis
plt.title("Any suitable title")  # Chart title
plt.show()
Enter fullscreen mode Exit fullscreen mode

Line Chart with Annotations

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]

plt.figure(figsize=(8, 6))
plt.plot(x, y, marker='o', linestyle='-')

# Add annotations
for i, (xi, yi) in enumerate(zip(x, y)):
    plt.annotate(f'({xi}, {yi})', (xi, yi), textcoords="offset points", xytext=(0, 10), ha='center')

plt.title('Line Chart with Annotations')
plt.xlabel('X-axis Label')
plt.ylabel('Y-axis Label')

plt.grid(True)
plt.show()
Enter fullscreen mode Exit fullscreen mode

*Multiple Line Charts Using Matplotlib *

import matplotlib.pyplot as plt
import numpy as np


x = np.array([1, 2, 3, 4])
y = x*2

plt.plot(x, y)
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.title("Any suitable title")
plt.show()  # show first chart

plt.figure()
x1 = [2, 4, 6, 8]
y1 = [3, 5, 7, 9]
plt.plot(x1, y1, '-.')
plt.show()
Enter fullscreen mode Exit fullscreen mode

Multiple Plots on the Same Axis

import matplotlib.pyplot as plt
import numpy as np

x = np.array([1, 2, 3, 4])
y = x*2

# first plot with X and Y data
plt.plot(x, y)

x1 = [2, 4, 6, 8]
y1 = [3, 5, 7, 9]

# second plot with x1 and y1 data
plt.plot(x1, y1, '-.')

plt.xlabel("X-axis data")
plt.ylabel("Y-axis data")
plt.title('multiple plots')
plt.show()
Enter fullscreen mode Exit fullscreen mode

Fill the Area Between Two Lines

import matplotlib.pyplot as plt
import numpy as np

x = np.array([1, 2, 3, 4])
y = x*2

plt.plot(x, y)

x1 = [2, 4, 6, 8]
y1 = [3, 5, 7, 9]

plt.plot(x, y1, '-.')
plt.xlabel("X-axis data")
plt.ylabel("Y-axis data")
plt.title('multiple plots')

plt.fill_between(x, y, y1, color='green', alpha=0.5)
plt.show()
Enter fullscreen mode Exit fullscreen mode

Bar Plot

import matplotlib.pyplot as plt
import numpy as np

fruits = ['Apples', 'Bananas', 'Cherries', 'Dates']
sales = [400, 350, 300, 450]

plt.bar(fruits, sales)
plt.title('Fruit Sales')
plt.xlabel('Fruits')
plt.ylabel('Sales')
plt.show()
Enter fullscreen mode Exit fullscreen mode

Customizing Bar Colors

import matplotlib.pyplot as plt
import numpy as np

fruits = ['Apples', 'Bananas', 'Cherries', 'Dates']
sales = [400, 350, 300, 450]

plt.bar(fruits, sales, color='violet')
plt.title('Fruit Sales')
plt.xlabel('Fruits')
plt.ylabel('Sales')
plt.show()
Enter fullscreen mode Exit fullscreen mode

Creating Horizontal Bar Plots

import matplotlib.pyplot as plt
import numpy as np

fruits = ['Apples', 'Bananas', 'Cherries', 'Dates']
sales = [400, 350, 300, 450]

plt.barh(fruits, sales)

plt.title('Fruit Sales')
plt.xlabel('Fruits')
plt.ylabel('Sales')
plt.show()
Enter fullscreen mode Exit fullscreen mode

Adjusting Bar width

import matplotlib.pyplot as plt
import numpy as np

fruits = ['Apples', 'Bananas', 'Cherries', 'Dates']
sales = [400, 350, 300, 450]

plt.bar(fruits, sales, width=0.3)
plt.title('Fruit Sales')
plt.xlabel('Fruits')
plt.ylabel('Sales')
plt.show()
Enter fullscreen mode Exit fullscreen mode

Multiple bar plots

import numpy as np 
import matplotlib.pyplot as plt 

barWidth = 0.25
fig = plt.subplots(figsize =(12, 8)) 

IT = [12, 30, 1, 8, 22] 
ECE = [28, 6, 16, 5, 10] 
CSE = [29, 3, 24, 25, 17] 

br1 = np.arange(len(IT)) 
br2 = [x + barWidth for x in br1] 
br3 = [x + barWidth for x in br2] 

plt.bar(br1, IT, color ='r', width = barWidth, 
        edgecolor ='grey', label ='IT') 
plt.bar(br2, ECE, color ='g', width = barWidth, 
        edgecolor ='grey', label ='ECE') 
plt.bar(br3, CSE, color ='b', width = barWidth, 
        edgecolor ='grey', label ='CSE') 

plt.xlabel('Branch', fontweight ='bold', fontsize = 15) 
plt.ylabel('Students passed', fontweight ='bold', fontsize = 15) 
plt.xticks([r + barWidth for r in range(len(IT))], 
        ['2015', '2016', '2017', '2018', '2019'])

plt.legend()
plt.show()
Enter fullscreen mode Exit fullscreen mode

Stacked bar chart

import numpy as np
import matplotlib.pyplot as plt

N = 5

boys = (20, 35, 30, 35, 27)
girls = (25, 32, 34, 20, 25)
boyStd = (2, 3, 4, 1, 2)
girlStd = (3, 5, 2, 3, 3)
ind = np.arange(N)   
width = 0.35  

fig = plt.subplots(figsize =(10, 7))
p1 = plt.bar(ind, boys, width, yerr = boyStd)
p2 = plt.bar(ind, girls, width,
             bottom = boys, yerr = girlStd)

plt.ylabel('Contribution')
plt.title('Contribution by the teams')
plt.xticks(ind, ('T1', 'T2', 'T3', 'T4', 'T5'))
plt.yticks(np.arange(0, 81, 10))
plt.legend((p1[0], p2[0]), ('boys', 'girls'))

plt.show()
Enter fullscreen mode Exit fullscreen mode

Matplotlib Scatter

import matplotlib.pyplot as plt
import numpy as np

x = np.array([12, 45, 7, 32, 89, 54, 23, 67, 14, 91])
y = np.array([99, 31, 72, 56, 19, 88, 43, 61, 35, 77])

plt.scatter(x, y)
plt.title("Basic Scatter Plot")
plt.xlabel("X Values")
plt.ylabel("Y Values")
plt.show()
Enter fullscreen mode Exit fullscreen mode

Example 1: In this example, we compare the height and weight of two different groups using different colors for each group.

x1 = np.array([160, 165, 170, 175, 180, 185, 190, 195, 200, 205])
y1 = np.array([55, 58, 60, 62, 64, 66, 68, 70, 72, 74])

x2 = np.array([150, 155, 160, 165, 170, 175, 180, 195, 200, 205])
y2 = np.array([50, 52, 54, 56, 58, 64, 66, 68, 70, 72])

plt.scatter(x1, y1, color='blue', label='Group 1')
plt.scatter(x2, y2, color='red', label='Group 2')

plt.xlabel('Height (cm)')
plt.ylabel('Weight (kg)')
plt.title('Comparison of Height vs Weight between two groups')
plt.legend()
plt.show()
Enter fullscreen mode Exit fullscreen mode

Example 2: This example demonstrates how to customize a scatter plot using different marker sizes and colors for each point. Transparency and edge colors are also adjusted.

x = np.array([3, 12, 9, 20, 5, 18, 22, 11, 27, 16])
y = np.array([95, 55, 63, 77, 89, 50, 41, 70, 58, 83])

a = [20, 50, 100, 200, 500, 1000, 60, 90, 150, 300] # size
b = ['red', 'green', 'blue', 'purple', 'orange', 'black', 'pink', 'brown', 'yellow', 'cyan'] # color

plt.scatter(x, y, s=a, c=b, alpha=0.6, edgecolors='w', linewidths=1)
plt.title("Scatter Plot with Varying Colors and Sizes")
plt.show()
Enter fullscreen mode Exit fullscreen mode

Example 3: This example shows how to create a bubble plot where the size of each point (bubble) represents a variable's magnitude. Edge color and alpha transparency are also used.

x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]
sizes = [30, 80, 150, 200, 300]  # Bubble sizes

plt.scatter(x, y, s=sizes, alpha=0.5, edgecolors='blue', linewidths=2)
plt.title("Bubble Plot Example")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.show()
Enter fullscreen mode Exit fullscreen mode

Example 4: In this example, we map data values to colors using a colormap and add a colorbar. This helps in visualizing a third variable via color intensity.

x = np.random.randint(50, 150, 100)
y = np.random.randint(50, 150, 100)
colors = np.random.rand(100)  # Random float values for color mapping
sizes = 20 * np.random.randint(10, 100, 100)

plt.scatter(x, y, c=colors, s=sizes, cmap='viridis', alpha=0.7)
plt.colorbar(label='Color scale')
plt.title("Scatter Plot with Colormap and Colorbar")
plt.show()
Enter fullscreen mode Exit fullscreen mode

Example 5: This final example illustrates how to change the marker style using the marker parameter. Here, triangle markers are used with magenta color.

plt.scatter(x, y, marker='^', color='magenta', s=100, alpha=0.7)
plt.title("Scatter Plot with Triangle Markers")
plt.show()
Enter fullscreen mode Exit fullscreen mode

*Plotting Histogram *

Different methods of plotting histogram

  • Basic Histogram
  • Customized Histogram with Density Plot
  • Customized Histogram with Watermark
  • Multiple Histograms with Subplots
  • Stacked Histogram
  • 2D Histogram (Hexbin Plot)
  1. Basic Histogram
import matplotlib.pyplot as plt
import numpy as np

# Generate random data for the histogram
data = np.random.randn(1000)

# Plotting a basic histogram
plt.hist(data, bins=30, color='skyblue', edgecolor='black')

# Adding labels and title
plt.xlabel('Values')
plt.ylabel('Frequency')
plt.title('Basic Histogram')

# Display the plot
plt.show()
Enter fullscreen mode Exit fullscreen mode
  1. Customized Histogram with Density Plot
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np

# Generate random data for the histogram
data = np.random.randn(1000)

# Creating a customized histogram with a density plot
sns.histplot(data, bins=30, kde=True, color='lightgreen', edgecolor='red')

# Adding labels and title
plt.xlabel('Values')
plt.ylabel('Density')
plt.title('Customized Histogram with Density Plot')

# Display the plot
plt.show()
Enter fullscreen mode Exit fullscreen mode
  1. Customized Histogram with Watermark
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import colors
from matplotlib.ticker import PercentFormatter

# Creating dataset
np.random.seed(23685752)
N_points = 10000
n_bins = 20

# Creating distribution
x = np.random.randn(N_points)
y = 0.8 ** x + np.random.randn(N_points) + 25
legend = ['distribution']

# Creating figure and axes
fig, axs = plt.subplots(1, 1, figsize=(10, 7), tight_layout=True)

# Remove axes splines
for s in ['top', 'bottom', 'left', 'right']:
    axs.spines[s].set_visible(False)

# Remove x, y ticks
axs.xaxis.set_ticks_position('none')
axs.yaxis.set_ticks_position('none')

# Add padding between axes and labels
axs.xaxis.set_tick_params(pad=5)
axs.yaxis.set_tick_params(pad=10)

# Add x, y gridlines (updated syntax)
axs.grid(visible=True, color='grey', linestyle='-.', linewidth=0.5, alpha=0.6)

# Add text watermark
fig.text(0.9, 0.15, 'Jeeteshgavande30',
         fontsize=12,
         color='red',
         ha='right',
         va='bottom',
         alpha=0.7)

# Creating histogram
N, bins, patches = axs.hist(x, bins=n_bins)

# Setting color gradient
fracs = ((N ** (1 / 5)) / N.max())
norm = colors.Normalize(fracs.min(), fracs.max())

for thisfrac, thispatch in zip(fracs, patches):
    color = plt.cm.viridis(norm(thisfrac))
    thispatch.set_facecolor(color)

# Adding extra features
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.legend(legend)
plt.title('Customized Histogram with Watermark')

# Show plot
plt.show()
Enter fullscreen mode Exit fullscreen mode
  1. Multiple Histograms with Subplots
import matplotlib.pyplot as plt
import numpy as np

# Generate random data for multiple histograms
data1 = np.random.randn(1000)
data2 = np.random.normal(loc=3, scale=1, size=1000)

# Creating subplots with multiple histograms
fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(12, 4))

axes[0].hist(data1, bins=30, color='Yellow', edgecolor='black')
axes[0].set_title('Histogram 1')

axes[1].hist(data2, bins=30, color='Pink', edgecolor='black')
axes[1].set_title('Histogram 2')

# Adding labels and title
for ax in axes:
    ax.set_xlabel('Values')
    ax.set_ylabel('Frequency')

# Adjusting layout for better spacing
plt.tight_layout()

# Display the figure
plt.show()
Enter fullscreen mode Exit fullscreen mode
  1. Stacked Histogram
import matplotlib.pyplot as plt
import numpy as np

# Generate random data for stacked histograms
data1 = np.random.randn(1000)
data2 = np.random.normal(loc=3, scale=1, size=1000)

# Creating a stacked histogram
plt.hist([data1, data2], bins=30, stacked=True, color=['cyan', 'Purple'], edgecolor='black')

# Adding labels and title
plt.xlabel('Values')
plt.ylabel('Frequency')
plt.title('Stacked Histogram')

# Adding legend
plt.legend(['Dataset 1', 'Dataset 2'])

# Display the plot
plt.show()
Enter fullscreen mode Exit fullscreen mode
  1. 2D Histogram (Hexbin Plot)
import matplotlib.pyplot as plt
import numpy as np

# Generate random 2D data for hexbin plot
x = np.random.randn(1000)
y = 2 * x + np.random.normal(size=1000)

# Creating a 2D histogram (hexbin plot)
plt.hexbin(x, y, gridsize=30, cmap='Blues')

# Adding labels and title
plt.xlabel('X values')
plt.ylabel('Y values')
plt.title('2D Histogram (Hexbin Plot)')

# Adding colorbar
plt.colorbar(label='Counts')

plt.show()
Enter fullscreen mode Exit fullscreen mode

Pie Chart

# Import libraries
from matplotlib import pyplot as plt
import numpy as np


# Creating dataset
cars = ['AUDI', 'BMW', 'FORD',
        'TESLA', 'JAGUAR', 'MERCEDES']

data = [23, 17, 35, 29, 12, 41]

# Creating plot
fig = plt.figure(figsize=(10, 7))
plt.pie(data, labels=cars)

# show plot
plt.show()
Enter fullscreen mode Exit fullscreen mode

Customizing Pie Charts

  • startangle: This attribute allows you to rotate the pie chart in Python counterclockwise around the x-axis by the specified degrees.. By adjusting this angle, you can change the starting position of the first wedge, which can improve the overall presentation of the chart.
  • shadow: This boolean attribute adds a shadow effect below the rim of the pie. Setting this to True can make your chart stand out and give it a more three-dimensional appearance, enhancing the overall look of your pie chart in Matplotlib.
  • wedgeprops: This parameter accepts a Python dictionary to customize the properties of each wedge in the pie chart. You can specify various attributes such as linewidth, edgecolor, and facecolor. This level of customization allows you to enhance the visual distinction between wedges, making your matplotlib pie chart more informative.
  • frame: When set to True, this attribute draws a frame around the pie chart. This can help emphasize the chart's boundaries and improve its visibility, making it clearer when presenting data. autopct: This attribute controls how the percentages are displayed on the wedges. You can customize the format string to define the appearance of the percentage labels on each slice. _The explode parameter separates a portion of the chart, and colors define each wedge's color. The autopct function customizes text display, and legend and title functions enhance chart readability and aesthetics. _
# Import libraries
import numpy as np
import matplotlib.pyplot as plt


# Creating dataset
cars = ['AUDI', 'BMW', 'FORD',
        'TESLA', 'JAGUAR', 'MERCEDES']

data = [23, 17, 35, 29, 12, 41]


# Creating explode data
explode = (0.1, 0.0, 0.2, 0.3, 0.0, 0.0)

# Creating color parameters
colors = ("orange", "cyan", "brown",
          "grey", "indigo", "beige")

# Wedge properties
wp = {'linewidth': 1, 'edgecolor': "green"}

# Creating autocpt arguments


def func(pct, allvalues):
    absolute = int(pct / 100.*np.sum(allvalues))
    return "{:.1f}%\n({:d} g)".format(pct, absolute)


# Creating plot
fig, ax = plt.subplots(figsize=(10, 7))
wedges, texts, autotexts = ax.pie(data,
                                  autopct=lambda pct: func(pct, data),
                                  explode=explode,
                                  labels=cars,
                                  shadow=True,
                                  colors=colors,
                                  startangle=90,
                                  wedgeprops=wp,
                                  textprops=dict(color="magenta"))

# Adding legend
ax.legend(wedges, cars,
          title="Cars",
          loc="center left",
          bbox_to_anchor=(1, 0, 0.5, 1))

plt.setp(autotexts, size=8, weight="bold")
ax.set_title("Customizing pie chart")

# show plot
plt.show()
Enter fullscreen mode Exit fullscreen mode

Nested Pie Chart:

# Import libraries
from matplotlib import pyplot as plt
import numpy as np


# Creating dataset
size = 6
cars = ['AUDI', 'BMW', 'FORD',
        'TESLA', 'JAGUAR', 'MERCEDES']

data = np.array([[23, 16], [17, 23],
                 [35, 11], [29, 33],
                 [12, 27], [41, 42]])

# normalizing data to 2 pi
norm = data / np.sum(data)*2 * np.pi

# obtaining ordinates of bar edges
left = np.cumsum(np.append(0,
                           norm.flatten()[:-1])).reshape(data.shape)

# Creating color scale
cmap = plt.get_cmap("tab20c")
outer_colors = cmap(np.arange(6)*4)
inner_colors = cmap(np.array([1, 2, 5, 6, 9,
                              10, 12, 13, 15,
                              17, 18, 20]))

# Creating plot
fig, ax = plt.subplots(figsize=(10, 7),
                       subplot_kw=dict(polar=True))

ax.bar(x=left[:, 0],
       width=norm.sum(axis=1),
       bottom=1-size,
       height=size,
       color=outer_colors,
       edgecolor='w',
       linewidth=1,
       align="edge")

ax.bar(x=left.flatten(),
       width=norm.flatten(),
       bottom=1-2 * size,
       height=size,
       color=inner_colors,
       edgecolor='w',
       linewidth=1,
       align="edge")

ax.set(title="Nested pie chart")
ax.set_axis_off()

# show plot
plt.show()
Enter fullscreen mode Exit fullscreen mode

Three-dimensional Plotting(3D Plot)

import matplotlib.pyplot as plt

fig = plt.figure()
ax = plt.axes(projection='3d')
plt.show()
Enter fullscreen mode Exit fullscreen mode
  1. 3d Line plot
from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax = plt.axes(projection='3d')

z = np.linspace(0, 1, 100)
x = z * np.sin(25 * z)
y = z * np.cos(25 * z)

ax.plot3D(x, y, z, 'green')
ax.set_title('3D Line Plot')
plt.show()
Enter fullscreen mode Exit fullscreen mode

  1. 3D Scatter plot
fig = plt.figure()
ax = plt.axes(projection='3d')

z = np.linspace(0, 1, 100)
x = z * np.sin(25 * z)
y = z * np.cos(25 * z)
c = x + y  # Color array based on x and y

ax.scatter(x, y, z, c=c)
ax.set_title('3D Scatter Plot')
plt.show()
Enter fullscreen mode Exit fullscreen mode

  1. Surface Plot
x = np.outer(np.linspace(-2, 2, 10), np.ones(10))
y = x.copy().T
z = np.cos(x**2 + y**3)

fig = plt.figure()
ax = plt.axes(projection='3d')
ax.plot_surface(x, y, z, cmap='viridis', edgecolor='green')
ax.set_title('Surface Plot')
plt.show()
Enter fullscreen mode Exit fullscreen mode

  1. Wireframe Plot
def f(x, y):
    return np.sin(np.sqrt(x**2 + y**2))

x = np.linspace(-1, 5, 10)
y = np.linspace(-1, 5, 10)
X, Y = np.meshgrid(x, y)
Z = f(X, Y)

fig = plt.figure()
ax = plt.axes(projection='3d')
ax.plot_wireframe(X, Y, Z, color='green')
ax.set_title('Wireframe Plot')
plt.show()
Enter fullscreen mode Exit fullscreen mode

  1. Contour plot in 3d This plot combines a 3D surface with contour lines to highlight elevation or depth. It helps visualize the function’s shape and gradient changes more clearly in 3D space.
def fun(x, y):
    return np.sin(np.sqrt(x**2 + y**2))

x = np.linspace(-10, 10, 40)
y = np.linspace(-10, 10, 40)
X, Y = np.meshgrid(x, y)
Z = fun(X, Y)

fig = plt.figure(figsize=(10, 8))
ax = plt.axes(projection='3d')
ax.plot_surface(X, Y, Z, cmap='cool', alpha=0.8)

ax.set_title('3D Contour Plot')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')

plt.show()
Enter fullscreen mode Exit fullscreen mode

  1. Surface Triangulation plot This plot uses triangular meshes to build a 3D surface from scattered or grid data. It's ideal when the surface is irregular or when using non-rectangular grids.
from matplotlib.tri import Triangulation

def f(x, y):
    return np.sin(np.sqrt(x**2 + y**2))

x = np.linspace(-6, 6, 30)
y = np.linspace(-6, 6, 30)
X, Y = np.meshgrid(x, y)
Z = f(X, Y)

tri = Triangulation(X.ravel(), Y.ravel())

fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')
ax.plot_trisurf(tri, Z.ravel(), cmap='cool', edgecolor='none', alpha=0.8)

ax.set_title('Surface Triangulation Plot')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')

plt.show()
Enter fullscreen mode Exit fullscreen mode

  1. Möbius Strip Plot

A Möbius strip is a one-sided surface with a twist—a famous concept in topology. This plot visualizes its 3D geometry, showing how math and art can blend beautifully.

R = 2
u = np.linspace(0, 2*np.pi, 100)
v = np.linspace(-1, 1, 100)
u, v = np.meshgrid(u, v)

x = (R + v * np.cos(u / 2)) * np.cos(u)
y = (R + v * np.cos(u / 2)) * np.sin(u)
z = v * np.sin(u / 2)

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

ax.plot_surface(x, y, z, alpha=0.5)

ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
ax.set_title('Möbius Strip')

ax.set_xlim([-3, 3])
ax.set_ylim([-3, 3])
ax.set_zlim([-3, 3])

plt.show()
Enter fullscreen mode Exit fullscreen mode

Top comments (0)