Skip to content

Instantly share code, notes, and snippets.

@AlexTitovWork
Last active March 6, 2024 09:12
Show Gist options
  • Save AlexTitovWork/d66584382619e5edba151867e41cba3e to your computer and use it in GitHub Desktop.
Save AlexTitovWork/d66584382619e5edba151867e41cba3e to your computer and use it in GitHub Desktop.
Plotting the Himmelblau function
import numpy as np
import matplotlib.pyplot as plt
# ################################################################################
def plot_function():
# Make data.
X = np.arange(-5, 5, 0.25)
Y = np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(X, Y)
Z = (X ** 2 + Y - 11) ** 2 + (X + Y ** 2 - 7) ** 2
# Plot the surface.
fig = plt.figure()
ax = fig.gca(projection='3d')
surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm,
linewidth=0, antialiased=False)
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
return X, Y, Z
# ################################################################################
X, Y, Z = plot_function()
@AlexTitovWork
Copy link
Author

  • change on public gist

@floffy-f
Copy link

floffy-f commented Mar 1, 2024

Thank you for the public code !
I think the gist may lack an import for the cm.coolwarm part.
You may want to use matplotlib.colormaps["coolwarm"] or an equivalent matplotlib.cm.coolwarm.

For 3D plots there is this line that works well in many cases:

fig, ax = plt.subplots(subplot_kw={'projection': '3d'})

@AlexTitovWork
Copy link
Author

Hello @floffy-f ! Yes, thanks a lot! I think it
fig, ax = plt.subplots(subplot_kw={'projection': '3d'})
may minimizes this code

@AlexTitovWork
Copy link
Author

new one

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D # It is important for 3d plot
# update by Alex
# 05.03.2024
# ################################################################################
def plot_function():
    # Make data.
    X = np.arange(-5, 5, 0.25)
    Y = np.arange(-5, 5, 0.25)
    X, Y = np.meshgrid(X, Y)
    Z = (X ** 2 + Y - 11) ** 2 + (X + Y ** 2 - 7) ** 2

    # Plot the surface.
    #     # fig = plt.figure()
    #     # ax = plt.axes(projection='3d')
    #  Eqvivalent code from @floffy-f
    fig, ax = plt.subplots(subplot_kw={'projection': '3d'})

    # Syntax for plotting
    # cmap = 'viridis'
    # cmap='coolwarm'
    ax.plot_surface(X, Y, Z, cmap='viridis', \
                    edgecolor='green', linewidth=0, antialiased=False)

    ax.set_xlabel('X Label')
    ax.set_ylabel('Y Label')
    ax.set_zlabel('Z Label')
    plt.show()
    return X, Y, Z
# ################################################################################
X, Y, Z = plot_function()```

@AlexTitovWork
Copy link
Author

изображение

@floffy-f
Copy link

floffy-f commented Mar 6, 2024

Perfect ! Thank you for your response and cool code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment