Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plotting a function of three variables in python

I would like to plot the contour lines for this function, however I cannot find any useful way to do it.

The potential function is : V(x,y,z) = cos(10x) + cos(10y) + cos(10z) + 2*(x^2 + y^2 + z^2)

I unsuccessfully attempted something like:

import numpy
import matplotlib.pyplot.contour

def V(x,y,z):
    return numpy.cos(10*x) + numpy.cos(10*y) + numpy.cos(10*z) + 2*(x**2 + y**2 + z**2)

X, Y, Z = numpy.mgrid[-1:1:100j, -1:1:100j, -1:1:100j]

But then, I don't know how to do the next step to plot it?

matplotlib.pyplot.contour(X,Y,Z,V)
like image 775
user3412058 Avatar asked May 27 '15 20:05

user3412058


People also ask

Can you plot a function in Python?

MatPlotLib with PythonCreate a user-defined function using, def, i.e., f(x). Create x data points using numpy. Plot x and f(x) using plot() method. To display the figure, use show() method.


1 Answers

An error will arise when you try to pass contour three-dimensional arrays, as it expects two-dimensional arrays.

With this in mind, try:

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

def V(x,y,z):
     return np.cos(10*x) + np.cos(10*y) + np.cos(10*z) + 2*(x**2 + y**2 + z**2)

X,Y = np.mgrid[-1:1:100j, -1:1:100j]
Z_vals = [ -0.5, 0, 0.9 ]
num_subplots = len( Z_vals)

fig = plt.figure(figsize=(10, 4))
for i,z in enumerate( Z_vals):
    ax = fig.add_subplot(1 , num_subplots , i+1, projection='3d')
    ax.contour(X, Y, V(X,Y,z), cmap=cm.gnuplot)
    ax.set_title('z = %.2f'%z, fontsize=30)
fig.savefig('contours.png', facecolor='grey', edgecolor='none')

enter image description here

Instead, use ax.contourf(...) to show the surfaces, which looks nicer in my opinion.

enter image description here

There is no direct way to visualize a function of 3 variables, as it is an object (surface) which lives in 4 dimensions. One must play with slices of the function to see what's going on. By a slice, I mean a projection of the function onto a lower dimensional space. A slice is achieved by setting one or more of the function variables as a constant.

like image 195
dermen Avatar answered Oct 17 '22 11:10

dermen