简体   繁体   中英

How to make a 3D data surface plot using matplotlib in python

I am trying to make a 3d surface plot of experimental data using matplotlib. I would like to plot different Z values against the same X and Y axes. When I try the simple code below, I get the error

"plot_surface() missing 1 required positional argument: 'Z' ".

It seems that the Axes3D package only work if Z is given as a function of X and Y, rather than an actual data matrix. Does anybody know a way around this?

Please note that the Zmatrix that I need is actual data, but I just used a random matrix for illustration here.

import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
fig = plt.figure()

X=[2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
Y= [0,2500,5000,7500,10000,15000,20000,25000,30000,35000,40000,45000,50000,55000,60000,65000,70000]

Zmatrix=np.random.rand(len(X),len(Y))


Axes3D.plot_surface(X,Y,Zmatrix)

There were sone issues with your code: First you have to get a mashgrid of X and Y (all combinations as matrices). Next swap len(X) and len(Y) inside the Zmatrix . And first define ax = Axes3D(plt.gcf()) and plot_surface afterwards on ax .

import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
fig = plt.figure()

X=[2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
Y= [0,2500,5000,7500,10000,15000,20000,25000,30000,35000,40000,45000,50000,55000,60000,65000,70000]
Xm, Ym = np.meshgrid(X, Y)
Zmatrix=np.random.rand(len(Y),len(X))

ax = Axes3D(plt.gcf())
ax.plot_surface(Xm, Ym, Zmatrix)

在此处输入图片说明

Here is an example of surface plot.

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

  def fun(x, y):
      return x**2 + y

  fig = plt.figure()
  ax = fig.add_subplot(111, projection='3d')
  x = y = np.arange(-3.0, 3.0, 0.05)
  X, Y = np.meshgrid(x, y)
  zs = np.array([fun(x,y) for x,y in zip(np.ravel(X), np.ravel(Y))])
  Z = zs.reshape(X.shape)

  ax.plot_surface(X, Y, Z)

  ax.set_xlabel('X Label')
  ax.set_ylabel('Y Label')
  ax.set_zlabel('Z Label')

  plt.show()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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