从数组绘制轮廓和颜色网格

问题描述

我是本科生,想根据数据进行可视化。我是python的初学者。我想使用 def tempp(self) 制作 def pRSS(self)contourf 但它说:

Traceback (most recent call last):
  File "C:\Program Files\Spyder\pkgs\tkinter\__init__.py",line 1705,in __call__
    return self.func(*args)
  File "C:\Users\ASUS\Downloads\adli\dah_bisa_piiiii.py",line 96,in <lambda>
    self.b1 = tk.Button(app,text = "Temperature",command = lambda : self.tempp())
  File "C:\Users\ASUS\Downloads\adli\dah_bisa_piiiii.py",line 187,in tempp
    self.ax.contourf(x_1yr,z_1yr,temp_1yr)
  File "C:\Program Files\Spyder\pkgs\matplotlib\__init__.py",line 1447,in inner
    return func(ax,*map(sanitize_sequence,args),**kwargs)
  File "C:\Program Files\Spyder\pkgs\matplotlib\axes\_axes.py",line 6335,in contourf
    contours = mcontour.QuadContourSet(self,*args,**kwargs)
  File "C:\Program Files\Spyder\pkgs\matplotlib\contour.py",line 816,in __init__
    kwargs = self._process_args(*args,line 1430,in _process_args
    x,y,z = self._contour_args(args,kwargs)
  File "C:\Program Files\Spyder\pkgs\matplotlib\contour.py",line 1488,in _contour_args
    x,z = self._check_xyz(args[:3],line 1519,in _check_xyz
    raise TypeError(f"Input z must be 2D,not {z.ndim}D")
TypeError: Input z must be 2D,not 1D

我已经尝试制作网格并使用“temp_1yr”变量添加 z 值,但错误TypeError: Input z must be 2D,not 1D

我想用 def prs(self) 制作 np.colormesh 但它说:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Program Files\Spyder\pkgs\tkinter\__init__.py",line 97,in <lambda>
    self.b2 = tk.Button(app,text = "Fase",command = lambda : self.phss())
  File "C:\Users\ASUS\Downloads\adli\dah_bisa_piiiii.py",line 251,in phss
    self.ax.imshow(phs_1yr)
  File "C:\Program Files\Spyder\pkgs\matplotlib\__init__.py",line 5523,in imshow
    im.set_data(X)
  File "C:\Program Files\Spyder\pkgs\matplotlib\image.py",line 712,in set_data
    .format(self._A.shape))
TypeError: Invalid shape (1727,) for image data

我尝试使用 ```np.rehsape`` 但我无法重塑,因为:

Traceback (most recent call last):

  File "C:\Program Files\Spyder\pkgs\numpy\core\fromnumeric.py",line 58,in _wrapfunc
    return bound(*args,**kwds)

TypeError: order must be str,not int


During handling of the above exception,another exception occurred:

Traceback (most recent call last):

  File "C:\Users\ASUS\Downloads\adli\nyoba misahin sama plot kontur.py",line 84,in <module>
    nilai = np.reshape(prs_1yr,(len(list_x)),(len(list_z)))

  File "<__array_function__ internals>",line 6,in reshape

  File "C:\Program Files\Spyder\pkgs\numpy\core\fromnumeric.py",line 299,in reshape
    return _wrapfunc(a,'reshape',newshape,order=order)

  File "C:\Program Files\Spyder\pkgs\numpy\core\fromnumeric.py",line 67,in _wrapfunc
    return _wrapit(obj,method,**kwds)

  File "C:\Program Files\Spyder\pkgs\numpy\core\fromnumeric.py",line 44,in _wrapit
    result = getattr(asarray(obj),method)(*args,not int

在那段代码中,我将 x 和 z 的唯一值分开并使用

nilai = np.reshape(prs_1yr,(len(list_z)))

原始代码在这里

matplotlib.use('TkAgg')
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import figureCanvasTkAgg
import tkinter as tk
import tkinter.filedialog as fd


class Application(tk.Frame):
    def __init__(self,master=None):
        tk.Frame.__init__(self,master)
        
        app.title("Post-Processor")
        app.configure(bg='#20bebe')
        app.geometry('500x150')
        app.resizable(False,False)
        
        self.sts = tk.Label(app,text="Status = data belum terinput")
        self.b0 = tk.Button(app,text = "Masukin Data",command = lambda : self.load())
        
        self.sts.config(width=30)
        self.b0.config(width=30)
        
        self.sts.place(x=250,y=15)
        self.b0.place(x=250,y=35)
        
        self.l0 = tk.Label(app,text="Program Visualisasi Hydrotherm")
        self.l1 = tk.Label(app,text="Tugas Akhir")
        self.l2 = tk.Label(app,text="Muhammad Adli - 1615051039")
        self.l3 = tk.Label(app,text="Teknik Geofisika Universitas Lampung")
        
        self.l0.config(width=30)
        self.l1.config(width=30,height=5)
        self.l2.config(width=30)
        self.l3.config(width=30)
        
        self.l0.place(x=10,y=20)
        self.l1.place(x=10,y=40)
        self.l2.place(x=10,y=90)
        self.l3.place(x=10,y=110)
        
        
    def load(self):
       
        self.filename = fd.askopenfilename(initialfile="Plot_scalar",filetypes=(("file",""),("all files",".*")))
        self.list_phs = np.loadtxt(self.filename,skiprows=5)
        
        #Data yang diambil dari plot
        self.x = self.list_phs[:,0]
        self.z = self.list_phs[:,2]
        self.yrs = self.list_phs[:,3]
        self.temp = self.list_phs[:,4]
        self.phs = self.list_phs[:,7]
        self.prs = self.list_phs[:,5]
        
        self.temp_yr = -1
        self.list_yr = []
        for it in self.yrs:
            if self.temp_yr != it:
                self.list_yr.append(it)
            self.temp_yr = it

        self.n_tstep = len(self.list_yr)
        
        self.sts = tk.Label(app,text="Status = data sudah terinput")
        self.sts.config(width=30)
        self.sts.place(x=250,y=15)
        
        self.b1 = tk.Button(app,command = lambda : self.tempp())
        self.b2 = tk.Button(app,command = lambda : self.phss())
        self.b3 = tk.Button(app,text = "Tekanan",command = lambda : self.pRSS())
       
        self.b1.config(width=30,height=1)
        self.b2.config(width=30,height=1)
        self.b3.config(width=30,height=1)
        
        self.b1.place(x=250,y=60)
        self.b2.place(x=250,y=85)
        self.b3.place(x=250,y=110)
    
    def pRSS(self): 
        
        #window baru
        vw = tk.Toplevel(app)
        vw.title('Hasil Pressure')
        vw.geometry('800x1600')
        
        #pembuatan data pressure
        self.it = 0
        fig = plt.figure(figsize = (8,8))
        
        #
        mask = self.yrs == self.list_yr[self.it]
        x_1yr = self.x[mask]
        z_1yr = self.z[mask]
        prs_1yr = self.prs[mask]
        
        self.ax = fig.add_subplot(111)
        self.ax.pcolourmesh(x_1yr,prs_1yr)
        self.ax.set_title(str(self.list_yr[self.it]) + " tahun")
        self.ax.set_xlabel('x (km)')
        self.ax.set_ylabel('z (km)')
        canvas = figureCanvasTkAgg(fig,master=vw)
        canvas.get_tk_widget().grid(row=0,column=1)
        canvas.draw()
        self.plotbutton=tk.Button(master=vw,text="prevIoUs",command=lambda: self.prevIoUs_pr(canvas,self.ax))
        self.plotbutton.grid(row=1,column=2)
        self.plotbutton2=tk.Button(master=vw,text="next",command=lambda: self.next_pr(canvas,self.ax))
        self.plotbutton2.grid(row=2,column=2)
        
    def next_pr(self,canvas,ax):
        if self.it == self.n_tstep:
            self.it = 0
        else:
            self.it += 1
        mask = self.yrs == self.list_yr[self.it]
        x_1yr = self.x[mask]
        z_1yr = self.z[mask]
        prs_1yr = self.prs[mask]
        
        self.ax.scatter(x_1yr,c=prs_1yr,facecolor=prs_1yr,s=15)
        self.ax.set_title(str(self.list_yr[self.it]) + " tahun")
        self.ax.set_xlabel('x (km)')
        self.ax.set_ylabel('z (km)')
        canvas.draw()

    def prevIoUs_pr(self,ax):
        if self.it == 0:
            self.it = self.n_tstep
        else:
            self.it -= 1
        mask = self.yrs == self.list_yr[self.it]
        x_1yr = self.x[mask]
        z_1yr = self.z[mask]
        prs_1yr = self.prs[mask]
        
        self.ax.scatter(x_1yr,s=15)
        self.ax.set_title(str(self.list_yr[self.it]) + " tahun")
        self.ax.set_xlabel('x (km)')
        self.ax.set_ylabel('z (km)')
        canvas.draw()

    def tempp(self): #mau diganti contur
        vw = tk.Toplevel(app)
        vw.title('Hasil Temperatur')
        vw.geometry('800x1600')
        
        self.it = 0
        fig = plt.figure(figsize = (8,8))
        
        mask = self.yrs == self.list_yr[self.it]
        x_1yr = self.x[mask]
        z_1yr = self.z[mask]
        temp_1yr = self.temp[mask]
             
        self.ax = fig.add_subplot(111)
        self.ax.contourf(x_1yr,temp_1yr)
        self.ax.set_title(str(self.list_yr[self.it]) + " tahun")
        self.ax.set_xlabel('x (km)')
        self.ax.set_ylabel('z (km)')
        
        canvas = figureCanvasTkAgg(fig,command=lambda: self.prevIoUs_t(canvas,command=lambda: self.next_t(canvas,column=2)
        
    def next_t(self,ax):
        if self.it == self.n_tstep:
            self.it = 0
        else:
            self.it += 1
        
        mask = self.yrs == self.list_yr[self.it]
        x_1yr = self.x[mask]
        z_1yr = self.z[mask]
        temp_1yr = self.temp[mask]
        
        self.ax.scatter(x_1yr,c=temp_1yr,facecolor=temp_1yr,s=15)
        self.ax.set_title(str(self.list_yr[self.it]) + " tahun")
        self.ax.set_xlabel('x (km)')
        self.ax.set_ylabel('z (km)')
        canvas.draw()

    def prevIoUs_t(self,ax):
        if self.it == 0:
            self.it = self.n_tstep
        else:
            self.it -= 1
        mask = self.yrs == self.list_yr[self.it]
        x_1yr = self.x[mask]
        z_1yr = self.z[mask]
        temp_1yr = self.temp[mask]
        
        self.ax.scatter(x_1yr,s=15)
        self.ax.set_title(str(self.list_yr[self.it]) + " tahun")
        self.ax.set_xlabel('x (km)')
        self.ax.set_ylabel('z (km)')
        canvas.draw()
        
    def phss(self): #mau diganti colormesh
        vw = tk.Toplevel(app)
        vw.title('Hasil Fase')
        vw.geometry('800x1600')
        
        self.it = 0
        fig=plt.figure(figsize=(8,8))
        mask = self.yrs == self.list_yr[self.it]
        x_1yr = self.x[mask]
        z_1yr = self.z[mask]
        phs_1yr = self.phs[mask]
        
        self.ax = fig.add_subplot(111)
        self.ax.imshow(phs_1yr)
        self.ax.set_title(str(self.list_yr[self.it]) + " tahun")
        self.ax.set_xlabel('x (km)')
        self.ax.set_ylabel('z (km)')
        
        canvas = figureCanvasTkAgg(fig,command=lambda: self.prevIoUs_p(canvas,command=lambda: self.next_p(canvas,column=2)
        
    def next_p(self,ax):
            
        if self.it == self.n_tstep:
            self.it = 0
        else:
            self.it += 1
        mask = self.yrs == self.list_yr[self.it]
        x_1yr = self.x[mask]
        z_1yr = self.z[mask]
        phs_1yr = self.phs[mask]
        
        self.ax.scatter(x_1yr,c=phs_1yr,facecolor=phs_1yr,s=15)
        self.ax.set_title(str(self.list_yr[self.it]) + " tahun")
        self.ax.set_xlabel('x (km)')
        self.ax.set_ylabel('z (km)')
        canvas.draw()

    def prevIoUs_p(self,ax):
        
        if self.it == 0:
            self.it = self.n_tstep
        else:
            self.it -= 1
        mask = self.yrs == self.list_yr[self.it]
        x_1yr = self.x[mask]
        z_1yr = self.z[mask]
        phs_1yr = self.phs[mask]
        
        self.ax.scatter(x_1yr,s=15)
        self.ax.set_title(str(self.list_yr[self.it]) + " tahun")
        self.ax.set_xlabel('x (km)')
        self.ax.set_ylabel('z (km)')
        canvas.draw()

app = tk.Tk()
mw=Application(master=app)
mw.mainloop()

并且在分离我使用的唯一值时:

matplotlib.use('TkAgg')
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import figureCanvasTkAgg
import tkinter as tk
import tkinter.filedialog as fd

filename = fd.askopenfilename(initialfile="Plot_scalar",".*")))
list_phs = np.loadtxt(filename,skiprows=5)
x = list_phs[:,0]
z = list_phs[:,2]
yrs = list_phs[:,3]
temp = list_phs[:,4]
phs = list_phs[:,7]
prs = list_phs[:,5]

print(z[0])

temp_yr = -1
list_yr = []
for yr in yrs:
    if temp_yr != yr:
        list_yr.append(yr)
    temp_yr = yr

# list_x = []
# temp_x = set(x)

# for u in

list_z =[]
temp_z = set(z)
tempkor_z = (list(temp_z))

for i in tempkor_z:
    list_z.append(i)
    
list_x =[]
temp_x = set(x)
tempkor_x = (list(temp_x))

for u in tempkor_x:
    list_x.append(u)
    
c = np.meshgrid(list_x,list_z)

编辑

抱歉,我忘记附上数据文件了。这是数据的链接

https://drive.google.com/file/d/1shhCGG_iIJK--r8BWzJnkFlx6J3SsluC/view?usp=sharing

编辑 V2

我一直在尝试将 x 和 z 分开并成功,但在重塑中它说:

ValueError: cannot reshape array of size 1727 into shape (64,34)

我正在使用

import matplotlib
matplotlib.use('TkAgg')
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import figureCanvasTkAgg
import tkinter as tk
import tkinter.filedialog as fd

list_phs = np.loadtxt('desktop/Plot_scalar.txt',5]

temp_yr = -1
list_yr = []
for yr in yrs:
    if temp_yr != yr:
        list_yr.append(yr)
    temp_yr = yr

list_z =[]
temp_z = set(z)
tempkor_z = (list(temp_z))

for i in tempkor_z:
    list_z.append(i)
    
list_x =[]
temp_x = set(x)
tempkor_x = (list(temp_x))

for q in tempkor_x:
    list_x.append(q)

c = np.meshgrid(list_x,list_z)


n_tstep = len(list_yr)

it = 0
mask = yrs == list_yr[it]
x_1yr = x[mask]
z_1yr = z[mask]
temp_1yr = temp[mask]

nilai = np.reshape(temp_1yr,(len(list_x),len(list_z)))

plt.contourf(list_x,list_z,nilai)
plt.show

绘制轮廓

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)