0

the value on y-axis does not change in my plot if I define my function outside ax.plot_wireframe(). It is the problem of my real function which longer.

import pandas
import numpy
from matplotlib import cm
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D # <--- This is important for 3d plotting 

a = numpy.linspace(1,10,10)  # x axis
b = numpy.linspace(1,10,10)  # y axis
R = a+b   #model function, real function is longer
z = R
    
fig = plt.figure()
ax = plt.axes(projection='3d')
a,b = numpy.meshgrid(a,b)
#ax.plot_wireframe(a,b,a+b, color='b') #correct
#ax.plot_wireframe(a,b,z, color='b') #wrong
ax.plot_wireframe(a,b,R, color='b') #wrong
ax.set_title('surface');
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z');

Here is the result enter image description here

Codelearner777
  • 313
  • 3
  • 15

1 Answers1

2

Take a look at the matplotlib documentation regarding 3D wireframe plots. The x, y and z values need to be 2-dimensional. Explanations for this are given here or here. This is also the reason for the line

a,b = numpy.meshgrid(a,b)

in your code. It creates a 10x10 2D array for both 1D inputs. In the next lines you call the wireframe method with a+b for the z values. Hence, the z values are calculated in place and the result is again a 10x10 2D array. The reason why you get the "wrong" graph with the variables R or z is that they are calculated before a and b are turned into their respective 2D meshgrids. If you define R or z after the line containing numpy.meshgrid it works fine.

import pandas
import numpy
from matplotlib import cm
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D # <--- This is important for 3d plotting 

a = numpy.linspace(1,10,10)  # x axis
b = numpy.linspace(1,10,10)  # y axis

R = a+b   #not working
z = R     #not working

def f(x,y): 
    return x+y

fig = plt.figure()
ax = plt.axes(projection='3d')
a,b = numpy.meshgrid(a,b)

Z = f(a,b)#working
R = a+b   #working
z = R     #working

#ax.plot_wireframe(a,b,a+b, color='b') #
#ax.plot_wireframe(a,b,Z, color='b') #
ax.plot_wireframe(a,b,R, color='b') #
ax.set_title('surface');
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z');

So the short answer is: numpy.meshgrid changes your variables a and b and your are basically doing your calculations with different as and bs

BenB
  • 658
  • 2
  • 10