Home > other >  Extracting data points (statistics) from matplotlib and equations
Extracting data points (statistics) from matplotlib and equations

Time:06-07

I have the following code that runs to a graph, what I want is to extract the X,Y and Z into a list (so I can copy them later in excel, and play with the numbers), basically the other way around of having a set of data and plotting it into a graph:

import matplotlib.pyplot as plt  
from mpl_toolkits.mplot3d import Axes3D  
from matplotlib import cm  
from matplotlib.ticker import LinearLocator, FormatStrFormatter  

import numpy as np

fig = plt.figure()
ax = fig.gca(projection='3d')
N = np.arange(0, 10, 1)
M = np.arange(0, 15, 1)
N, M = np.meshgrid(N, M)
DNM = 3992.88*N - 2585.96*M

surf = ax.plot_surface(N, M, DNM, rstride=1, cstride=1, cmap=cm.jet,
        linewidth=0, antialiased=False)
ax.set_zlim(-25000, 20000)

ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))

fig.colorbar(surf, shrink=0.5, aspect=10)

plt.show()

CodePudding user response:

First you need to convert your 2d array dnm to a x-y-z format:

n, m = dnm.shape
rows, cols = np.mgrid[:n,:m]
xyz = np.column_stack((rows.ravel(), cols.ravel(), dnm.ravel()))

Then you can write the resulting array xyz into an excel file using pandas:

import pandas as pd

df = pd.DataFrame(xyz)
xyz_path = "xyz.xlsx"
df.to_excel(xyz_path, index=False)

CodePudding user response:

You already have the x, y and z that you used to plot the figure. They are named N, M, DNM in your code. But these are 2D arrays, so all you have to do is convert them into 1D arrays for easy plot and manipulation inside Excel.

x, y, z = N.ravel(), M.ravel(), DNM.ravel()

Now, if you want to limit the z-range, apply logical indexing -25000 ≤ z ≤ 20000 like this:

limits = np.logical_and(z >= -25000, z <= 20000)
x, y, z = x[limits], y[limits], z[limits]

Finally, you can save as text using np.savetxt or save to an Excel file as @blunova did:

import pandas as pd

xyz = np.column_stack((x, y, z))
df = pd.DataFrame(xyz)
xyz_path = "xyz.xlsx"
df.to_excel(xyz_path, index=False)
  • Related