简体   繁体   English

Passing 3 arrays to matplotlib.pyplot.plot function in python

[英]Passing 3 arrays to matplotlib.pyplot.plot function in python

I noticed something unusual with a code I wrote that I didn't understand.我注意到我写的代码有些不寻常,但我不明白。 The problem was to plot a contour plot in python.问题出在 python 中的 plot 轮廓 plot 上。 Here is the code I wrote(Which is mistakenly wrong since I have to pass the plt.contour() instead of plt.plot() ):这是我编写的代码(这是错误的,因为我必须通过plt.contour()而不是plt.plot() ):

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

def f(x,y):
    return (x**2+y**2)/np.sqrt(x**2+y**2)
    
x=np.linspace(0,1,11)
y=np.linspace(0,1,11)



X,Y=np.meshgrid(x,y)
z=f(X,Y)
print(np.shape(z))


plt.plot(x,y,z)
plt.show()

Now, I though that this programme would throw an error since x and y are 1-D array and z is 11×11 array.现在,我认为这个程序会抛出一个错误,因为 x 和 y 是一维数组,而 z 是 11×11 数组。 However,to my surprise it didn't.然而,令我惊讶的是它没有。 Instead it plotted the curves as shown below:相反,它绘制了如下所示的曲线: 在此处输入图像描述

I checked the official documentation and according to it,this call is perfectly allowed.我检查了官方文档,根据它,这个调用是完全允许的。 However, the trouble part is I don't know what the code actually did.但是,麻烦的是我不知道代码实际上做了什么。 Why are the curves actually plotted like the one in figure given below?为什么曲线实际上如下图所示? There is no mention in official documentation that how such call to the function works.官方文档中没有提到对 function 的这种调用是如何工作的。 Can someone explain what this code actually did?有人可以解释这段代码实际上做了什么吗? I have hard time understanding this.我很难理解这一点。

Is this what you are trying to plot?这是您要尝试的 plot 吗?

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

def f(x,y):
    return (x**2+y**2)/np.sqrt(x**2+y**2)
    
x=np.linspace(0,1,11)
y=np.linspace(0,1,11)

X,Y=np.meshgrid(x,y)
z=f(X,Y)
 
fig = plt.figure()              #<----
ax = plt.axes(projection='3d')  #<----
ax.contour3D(X, Y, z)           #<----
plt.show()

在此处输入图像描述


Regarding the lack of an error/warning:关于缺少错误/警告:

Why are the curves actually plotted like the one in figure given below?为什么曲线实际上如下图所示?

Check this out for details What does the third parameter of plt.plot() in matplotlib do?详细请看这里 matplotlib 中 plt.plot() 的第三个参数是做什么的?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM