在python中绘制三个变量的函数 [英] Plotting a function of three variables in python

查看:127
本文介绍了在python中绘制三个变量的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为此功能绘制轮廓线,但是找不到任何有用的方法.

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

势函数为: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)

推荐答案

当您尝试传递 contour 三维数组时会出现错误,因为它需要二维数组.

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', axisbg='gray')
    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')

您可以改用 contourf 来显示表面,在我看来这看起来更好.

You can use instead contourf to show the surfaces, which looks nicer in my opinion.

进行一些详细说明(这可能超出了堆栈溢出的范围,但可能有助于解释前面的代码):

A little elaboration (which is probably beyond the scope of stack overflow, but might help explain the preceding code):

您可能知道,没有直接的方法可以将 3 个变量的函数可视化,因为它是一个存在于 4 个维度中的对象(表面).相反,必须使用函数的片段来查看发生了什么.所谓切片,是指函数在较低维空间上的投影.切片是通过将一个或多个函数变量设置为常量来实现的.

As you may know, there is no direct way to visualize a function of 3 variables, as it is an object (surface) which lives in 4 dimensions. One instead must play with slices of the function to see whats 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.

这篇关于在python中绘制三个变量的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆