0

I am undergraduate students and want to make visualization from data. I am beginner in python. and i want to make the def tempp(self) and def prss(self) using contourf but it says:

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, **kwargs)
  File "C:\Program Files\Spyder\pkgs\matplotlib\contour.py", 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, y, z = self._check_xyz(args[:3], kwargs)
  File "C:\Program Files\Spyder\pkgs\matplotlib\contour.py", 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

i've been tried to make meshgrid and add z value with "temp_1yr" variable but error same with TypeError: Input z must be 2D, not 1D

and i want to make def prs(self) with np.colormesh but it says:

Exception in Tkinter callback
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 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 1447, in inner
    return func(ax, *map(sanitize_sequence, args), **kwargs)
  File "C:\Program Files\Spyder\pkgs\matplotlib\axes\_axes.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

i tried using ```np.rehsape`` but i couldn't reshape because:

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, *args, **kwds)

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

TypeError: order must be str, not int

in that code, i am separating x and z unique value and reshape with

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

the original code is here:

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, text = "Temperature", command = lambda : self.tempp())
        self.b2 = tk.Button(app, text = "Fase", 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, z_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,z_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, canvas, 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,z_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 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, z_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, 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_t(canvas,self.ax))
        self.plotbutton.grid(row=1,column=2)
        self.plotbutton2=tk.Button(master=vw, text="next", command=lambda: self.next_t(canvas,self.ax))
        self.plotbutton2.grid(row=2,column=2)
        
    def next_t(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]
        temp_1yr = self.temp[mask]
        
        self.ax.scatter(x_1yr,z_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, canvas, 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, z_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 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, 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_p(canvas,self.ax))
        self.plotbutton.grid(row=1,column=2)
        self.plotbutton2=tk.Button(master=vw, text="next", command=lambda: self.next_p(canvas,self.ax))
        self.plotbutton2.grid(row=2,column=2)
        
    def next_p(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]
        phs_1yr = self.phs[mask]
        
        self.ax.scatter(x_1yr,z_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, canvas, 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,z_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()

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

and in separating unique values i'm using:

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", filetypes=(("file", ""),("all files", ".*")))
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)

EDIT

Sorry, i'm forget to attach the data file. here is the link of the data:

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

EDIT V2

i've been trying to separate the x and z and sucessful, but in the reshape it says:

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

i'm using

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',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]

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

to make a contour

AvadEuros
  • 1
  • 2
  • 1
    Please provide a minimal self contained reproducible example that produces the error. This debugging step is crucial and will almost certainly reveal your problem. – Jody Klymak Mar 21 '21 at 16:50
  • Maybe you want `nilai = np.reshape(prs_1yr, (len(list_x), len(list_z)))`. Then you'd have two parameters: one array to be reshaped, and one tuple with the new shape. The original code has 3 parameters where `len(list_z)` is interpreted as the `order=` parameter for `np.reshape` – JohanC Mar 21 '21 at 17:33

0 Answers0