Python Matplotlib Mandelbrot Visualization

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

This lab will guide you through generating a shaded and power-normalized rendering of the Mandelbrot set using Python's Matplotlib library.

VM Tips

After the VM startup is done, click the top left corner to switch to the Notebook tab to access Jupyter Notebook for practice.

Sometimes, you may need to wait a few seconds for Jupyter Notebook to finish loading. The validation of operations cannot be automated because of limitations in Jupyter Notebook.

If you face issues during learning, feel free to ask Labby. Provide feedback after the session, and we will promptly resolve the problem for you.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/FileHandlingGroup(["`File Handling`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/BasicConceptsGroup(["`Basic Concepts`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/PlottingDataGroup(["`Plotting Data`"]) python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python(("`Python`")) -.-> python/ModulesandPackagesGroup(["`Modules and Packages`"]) python(("`Python`")) -.-> python/PythonStandardLibraryGroup(["`Python Standard Library`"]) python(("`Python`")) -.-> python/DataScienceandMachineLearningGroup(["`Data Science and Machine Learning`"]) python/FileHandlingGroup -.-> python/with_statement("`Using with Statement`") matplotlib/BasicConceptsGroup -.-> matplotlib/importing_matplotlib("`Importing Matplotlib`") matplotlib/BasicConceptsGroup -.-> matplotlib/figures_axes("`Understanding Figures and Axes`") matplotlib/PlottingDataGroup -.-> matplotlib/heatmaps("`Heatmaps`") python/BasicConceptsGroup -.-> python/variables_data_types("`Variables and Data Types`") python/BasicConceptsGroup -.-> python/numeric_types("`Numeric Types`") python/BasicConceptsGroup -.-> python/booleans("`Booleans`") python/ControlFlowGroup -.-> python/for_loops("`For Loops`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/FunctionsGroup -.-> python/default_arguments("`Default Arguments`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/ModulesandPackagesGroup -.-> python/using_packages("`Using Packages`") python/ModulesandPackagesGroup -.-> python/standard_libraries("`Common Standard Libraries`") python/PythonStandardLibraryGroup -.-> python/data_collections("`Data Collections`") python/DataScienceandMachineLearningGroup -.-> python/numerical_computing("`Numerical Computing`") python/DataScienceandMachineLearningGroup -.-> python/data_visualization("`Data Visualization`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/with_statement -.-> lab-48818{{"`Python Matplotlib Mandelbrot Visualization`"}} matplotlib/importing_matplotlib -.-> lab-48818{{"`Python Matplotlib Mandelbrot Visualization`"}} matplotlib/figures_axes -.-> lab-48818{{"`Python Matplotlib Mandelbrot Visualization`"}} matplotlib/heatmaps -.-> lab-48818{{"`Python Matplotlib Mandelbrot Visualization`"}} python/variables_data_types -.-> lab-48818{{"`Python Matplotlib Mandelbrot Visualization`"}} python/numeric_types -.-> lab-48818{{"`Python Matplotlib Mandelbrot Visualization`"}} python/booleans -.-> lab-48818{{"`Python Matplotlib Mandelbrot Visualization`"}} python/for_loops -.-> lab-48818{{"`Python Matplotlib Mandelbrot Visualization`"}} python/lists -.-> lab-48818{{"`Python Matplotlib Mandelbrot Visualization`"}} python/tuples -.-> lab-48818{{"`Python Matplotlib Mandelbrot Visualization`"}} python/function_definition -.-> lab-48818{{"`Python Matplotlib Mandelbrot Visualization`"}} python/default_arguments -.-> lab-48818{{"`Python Matplotlib Mandelbrot Visualization`"}} python/importing_modules -.-> lab-48818{{"`Python Matplotlib Mandelbrot Visualization`"}} python/using_packages -.-> lab-48818{{"`Python Matplotlib Mandelbrot Visualization`"}} python/standard_libraries -.-> lab-48818{{"`Python Matplotlib Mandelbrot Visualization`"}} python/data_collections -.-> lab-48818{{"`Python Matplotlib Mandelbrot Visualization`"}} python/numerical_computing -.-> lab-48818{{"`Python Matplotlib Mandelbrot Visualization`"}} python/data_visualization -.-> lab-48818{{"`Python Matplotlib Mandelbrot Visualization`"}} python/build_in_functions -.-> lab-48818{{"`Python Matplotlib Mandelbrot Visualization`"}} end

Import Required Libraries

First, we need to import the libraries we will be using: NumPy, Matplotlib, and Colors.

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import colors

Define the Mandelbrot Set Function

Next, we will define a function that generates the Mandelbrot set. The function takes in several parameters:

  • xmin, xmax, ymin, ymax: the minimum and maximum values for the x and y axes
  • xn and yn: the number of points to generate along each axis
  • maxiter: the maximum number of iterations to perform for each point
  • horizon: the maximum value at which to consider a point to be part of the set
def mandelbrot_set(xmin, xmax, ymin, ymax, xn, yn, maxiter, horizon=2.0):
    X = np.linspace(xmin, xmax, xn).astype(np.float32)
    Y = np.linspace(ymin, ymax, yn).astype(np.float32)
    C = X + Y[:, None] * 1j
    N = np.zeros_like(C, dtype=int)
    Z = np.zeros_like(C)
    for n in range(maxiter):
        I = abs(Z) < horizon
        N[I] = n
        Z[I] = Z[I]**2 + C[I]
    N[N == maxiter-1] = 0
    return Z, N

Generate the Mandelbrot Set

Now we will generate the Mandelbrot set by calling the mandelbrot_set function with our desired parameters. This will give us two arrays:

  • Z: the final values of the complex numbers we iterated over
  • N: the number of iterations performed for each point before it was determined to be part of the set
xmin, xmax, xn = -2.25, +0.75, 3000 // 2
ymin, ymax, yn = -1.25, +1.25, 2500 // 2
maxiter = 200
horizon = 2.0 ** 40
log_horizon = np.log2(np.log(horizon))
Z, N = mandelbrot_set(xmin, xmax, ymin, ymax, xn, yn, maxiter, horizon)

Normalize the Data

In order to create a shaded and power-normalized rendering of the Mandelbrot set, we need to normalize our data. We will do this using the following formula:

M = N + 1 - np.log2(np.log(abs(Z))) + log_horizon

with np.errstate(invalid='ignore'):
    M = np.nan_to_num(N + 1 - np.log2(np.log(abs(Z))) + log_horizon)

Create the Plot

Now that we have our normalized data, we can create the plot. We will use the imshow function to display the data as an image, and we will also add some text to the plot to indicate what we are looking at.

dpi = 72
width = 10
height = 10*yn/xn
fig = plt.figure(figsize=(width, height), dpi=dpi)
ax = fig.add_axes([0, 0, 1, 1], frameon=False, aspect=1)

light = colors.LightSource(azdeg=315, altdeg=10)
M = light.shade(M, cmap=plt.cm.hot, vert_exag=1.5,
                norm=colors.PowerNorm(0.3), blend_mode='hsv')
ax.imshow(M, extent=[xmin, xmax, ymin, ymax], interpolation="bicubic")
ax.set_xticks([])
ax.set_yticks([])

year = time.strftime("%Y")
text = ("The Mandelbrot fractal set\n"
        "Rendered with matplotlib %s, %s - https://matplotlib.org"
        % (matplotlib.__version__, year))
ax.text(xmin+.025, ymin+.025, text, color="white", fontsize=12, alpha=0.5)

plt.show()

Summary

In this lab, we learned how to generate a shaded and power-normalized rendering of the Mandelbrot set using Python's Matplotlib library. We accomplished this by defining a function to generate the set, normalizing the data, and creating a plot using the normalized data. This technique can be applied to other data sets to create visually appealing and informative images.

Other Python Tutorials you may like