Reputation: 3437
I'm looking for a way to fit some 3D data to a function and plot it using Python.
This tutorial describes how to plot a 3D surface but it assumes that we know the function describing the surface.
How can i import the data below and plot it using the plot_surface function (without knowing that z = x*y in this case)?
x 1 2 3 4
y
1 1 2 3 4
2 2 4 6 8
3 3 6 9 12
4 4 8 12 16
5 5 10 15 20
Upvotes: 0
Views: 668
Reputation: 339310
The data format is not very convenient to work with, but here is a way to read in the data, ignoring the coordinates and regenerating them afterwards.
import io
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
d = u""" x 1 2 3 4
y
1 1 2 3 4
2 2 4 6 8
3 3 6 9 12
4 4 8 12 16
5 5 10 15 20"""
s = io.StringIO(d)
a = np.loadtxt(s, skiprows=2)
Z = a[:,1:] # ignore first column
x = np.arange(1,Z.shape[1]+1)
y = np.arange(1,Z.shape[0]+1)
X,Y = np.meshgrid(x,y)
fig = plt.figure()
ax = fig.gca(projection='3d')
surf = ax.plot_surface(X, Y, Z, cmap=plt.cm.coolwarm,
linewidth=0, antialiased=False)
plt.show()
Upvotes: 1