[英]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.我有一个数据文件,其中有 3 列代表 x、y 和 z 值。 The z points are derived from a relation between x and y (so for each couple x[i]y[i] there is az[i]). z 点源自 x 和 y 之间的关系(因此对于每对 x[i]y[i],都有 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.我想使用 Matplotlib 获得轮廓 plot 并用 z 值着色表面,然后类似地使用 3D Z322AA46E1B78A96A4D。 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.在很多示例中,我已经看到可以使用 numpy 来网格化 x 和 y(由于数据量巨大,我无法做到这一点),然后将 z 定义为 f(x,y) 但是,正如我所说,我已经有了 x 和 y 的 z 值。 With GnuPlot is quite simple do that but in this case I cannot really understand how it does.使用 GnuPlot 很简单,但在这种情况下,我无法真正理解它是如何工作的。 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###
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.