1

I am trying to plot a 2 variable function with additional parameters which can be changed. Below is the function-

f(x,y) = (x - a*y)/(b+y)

I want to plot it in 3d and would like to see the change in the plot by changing the values of a and b, i.e. when a=1 and b=0, etc.

I can plot it for specific a and b cases, below is the code that works for a=1 and b=0. Is there any way where I don't need to map separately for different cases of a and b?

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

x = np.linspace(30,7000,10000)
y = np.linspace(1,11000, 10000)

def delCAD(x,y):
    return (x-y)/(y) # the function when a=1 and b=0

fig = plt.figure(figsize=(12,8))
ax = Axes3D(fig)
ax = fig.gca(projection = "3d")
surf = ax.plot_trisurf(x, y, delCAD(x,y), cmap = cm.coolwarm)
fig.colorbar(surf, shrink=0.5, aspect=5)
plt.show()
4
  • look if this is usefull in your case here Commented Jul 28, 2021 at 5:24
  • 1
    @BrunoMagacho unfortunately the slider widget doesnt work in 3D Commented Jul 28, 2021 at 12:17
  • You need to include your imports & all your code for instance delCAD_con() is missing Commented Jul 28, 2021 at 12:22
  • @DrBwts The slider widget DOES work in 3D Commented Jul 28, 2021 at 15:10

1 Answer 1

4

I generally use IPython or Jupyter for that sort of thing — maybe that's an option for you? For example, using ipywidgets.interact():

import matplotlib.pyplot as plt
import numpy as np
from ipywidgets import interact


x = np.linspace(1, 20, 50)
y = np.linspace(1, 20, 50)

y, x = np.meshgrid(y, x) 

def delCAD(x, y, a=1, b=0):
    return (x - a * y) / (b + y)

@interact(a=(1, 10), b=(0, 10))
def plot(a, b):
    fig, ax = plt.subplots(subplot_kw={"projection": "3d"}, figsize=(12, 6))
    surf = ax.plot_trisurf(x.flat, y.flat, delCAD(x, y, a, b).flat, cmap='coolwarm')
    fig.colorbar(surf, ax=ax, shrink=0.5, aspect=5)
    ax.view_init(elev=30, azim=160)
    plt.show()
    return

Produces this:

Output of script

As well as the interact wrapper, I introduced the meshgrid line to compute all the locations in the grid, and I changed some of your parameters a bit so you can see more going on in the function. I hope you can unpick the various pieces to fit your needs.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.