简体   繁体   中英

How can I obtain a contour plot and a 3D plot using Matplotlib starting from a set of 3 columns representing x,y and z points?

I have a data file in which there are 3 columns representing the x, y and z values. The z points are derived from a relation between x and y (so for each couple x[i]y[i] there is az[i]). I'd like, using Matplotlib, to obtain a contour plot and coloring the surface by z values and then similarly a 3D plot. In lot of examples I've seen that it's possible to use numpy to meshgrid x and y (something that I cannot do because the huge amount of data) and then define z as f(x,y) but, as I said, I already have the z values for x and y. With GnuPlot is quite simple do that but in this case I cannot really understand how it does. Can you please help? Thank you in advance

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

data=pd.read_csv('data.dat')
x=np.array(data.iloc[:,0])
y=np.array(data.iloc[:,1])
z=np.array(data.iloc[:,2])

contour = plt.tricontour(x, y, z, 20, colors='k', extent=[min(x), max(x), min(y), max(y)], origin='lower', alpha=0.3) #obtain contour plot

plt.imshow(z, extent=[min(x), max(x), min(y), max(y)], origin='lower') #of course here comes the error about the shape of z

I solved as follow:

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

###read file and set variables##
df=pd.read_csv('file.dat') #with some parameters#
D=df.iloc[:,:3]

x=np.array(D.iloc[:,0])
y=np.array(D.iloc[:,1])
z=np.array(D.iloc[:,2])

cv1=np.array(x[0:len(x):100])
cv2=np.array(y[0:len(y):100])*(180/np.pi)
fes=np.array(z[0:len(z):100])

### set plot ###
m=cm.ScalarMappable(cmap=cm.coolwarm)
m.set_array([min(fes),max(fes)])
m.set_clim(vmin=min(fes),vmax=max(fes))

fig=plt.figure()
surf=plt.axes(projection='3d')
surf.plot_trisurf(cv1,cv2,fes, cmap='coolwarm')

plt.tricontour(cv1,cv2,fes, colors='k', zdir='z', offset=-np.abs(min(z)), alpha=0.3)
plt.tricontourf(cv1,cv2,fes, cmap='coolwarm', zdir='z', offset=-np.abs(min(z)))

###finally set labels, ticks and colorbar###

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