Python 在tkinter GUI中嵌入matplotlib

Python 在tkinter GUI中嵌入matplotlib,python,python-3.x,matplotlib,user-interface,tkinter,Python,Python 3.x,Matplotlib,User Interface,Tkinter,试图在tkinter GUI中嵌入matplotlib,但出现错误: TypeError:init()为参数“master”获取了多个值 你能告诉我怎么处理吗 代码如下: 界面-tkinter GUI 可视化工具-使用pylive_mod文件中的函数live_绘图仪的selv更新图形 界面: # -*- coding: utf-8 -*- """ Created on Tue Oct 6 10:24:35 2020 @author: Dar0 "

试图在tkinter GUI中嵌入matplotlib,但出现错误:

TypeError:init()为参数“master”获取了多个值

你能告诉我怎么处理吗

代码如下:

界面-tkinter GUI

可视化工具-使用pylive_mod文件中的函数live_绘图仪的selv更新图形

界面:

    # -*- coding: utf-8 -*-
"""
Created on Tue Oct  6 10:24:35 2020

@author: Dar0
"""

from tkinter import * #import tkinter module
from visualizer import main #import module 'visualizer' that shows the graph in real time

class Application(Frame):
    ''' Interface for visualizing graphs, indicators and text-box. '''
    def __init__(self, master):
        super(Application, self).__init__(master)
        self.grid()
        self.create_widgets()
    
    def create_widgets(self):
        # Label of the 1st graph
        Label(self,
              text='Hook Load / Elevator Height / Depth vs Time'
              ).grid(row = 0, column = 0, sticky = W)
        
        # Graph 1 - Hook Load / Elevator Height / Depth vs Time
        # button that displays the plot 
        plot_button = Button(self,
                             master = root,
                             command = main,
                             height = 2, 
                             width = 10, 
                             text = "Plot").grid(row = 1, column = 0, sticky = W)

        # place the button 
        # in main window 
        
        # Label of the 2nd graph
        Label(self,
              text = 'Hook Load / Elevator Height vs Time'
              ).grid(row = 2, column = 0, sticky = W)
        
        # Graph 2 - Hook Load / Elevator Height vs Time
        
        #Label of the 3rd graph
        Label(self,
              text = 'Hook Load vs Time'
              ).grid(row = 4, column = 0, sticky = W)
        
        #Graph 3 - Hook Load vs Time
        
        #Label of the 1st indicator
        Label(self,
              text = '1st performance indicator'
              ).grid(row = 0, column = 1, sticky = W)
        
        #1st performance indicator
        
        #Label of 2nd performance indicator
        Label(self,
              text = '2nd performance indicator'
              ).grid(row = 2, column = 1, sticky = W)
        
        #2nd performance indicator
        
        #Label of 3rd performance indicator
        Label(self,
              text = '3rd performance indicator'
              ).grid(row = 4, column = 1, sticky = W)
        
        #Text-box showing comments based on received data
        self.text_box = Text(self, width = 50, height = 10, wrap = WORD)
        self.text_box.grid(row = 6, column = 0, columnspan = 1)
        self.text_box.delete(0.0, END)
        self.text_box.insert(0.0, 'My message will be here.')
        
#Main part
root = Tk()
root.title('WiTSML Visualizer by Dar0')
app = Application(root)
root.mainloop()
#WiTSML visualizer
#Created by Dariusz Krol
#import matplotlib
#matplotlib.use('TkAgg')
#from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
#from matplotlib.figure import Figure

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

class Visualizer(object):
    """ Includes all the methods needed to show streamed data. """
    def __init__(self):
        self.file_path = 'C:/Anaconda/_my_files/witsml_reader/modified_witsml.csv' #Defines which file is streamed

        self.datetime_mod = []
        self.bpos_mod = []
        self.woh_mod = []
        self.torq_mod = []
        self.spp_mod = []
        self.depth_mod = []
        self.flow_in_mod = []
        self.rpm_mod = []

    def open_file(self):
        self.df = pd.read_csv(self.file_path, low_memory = False, nrows = 300000) #Opens the STREAMED file (already modified so that data convert is not required)
        self.df = self.df.drop(0)
        self.df = pd.DataFrame(self.df)

        return self.df

    def convert_dataframe(self):
        self.df = self.df.values.T.tolist() #Do transposition of the dataframe and convert to list
        #Columns are as following:
        # - DATETIME
        # - BPOS
        # - WOH
        # - TORQ
        # - SPP
        # - DEPTH
        # - FLOW_IN
        # - RPM
        self.datetime_value = self.df[0]
        self.bpos_value = self.df[1]
        self.woh_value = self.df[2]
        self.torq_value = self.df[3]
        self.spp_value = self.df[4]
        self.depth_value = self.df[5]
        self.flow_in_value = self.df[5]
        self.rpm_value = self.df[7]

        return self.datetime_value, self.bpos_value, self.woh_value, self.torq_value, self.spp_value, self.depth_value, self.flow_in_value, self.rpm_value
        #print(self.bpos_value)

    def deliver_values(self, no_dp, columns):
        ''' Method gets no_dp amount of data points from the original file. '''
        self.no_dp = no_dp #defines how many data points will be presented in the graph

        val_dict = {
            'datetime': [self.datetime_value, self.datetime_mod],
            'bpos': [self.bpos_value, self.bpos_mod],
            'woh': [self.woh_value, self.woh_mod],
            'torq': [self.torq_value, self.torq_mod],
            'spp': [self.spp_value, self.spp_mod],
            'depth': [self.depth_value, self.depth_mod],
            'flow_in': [self.flow_in_value, self.flow_in_mod],
            'rpm': [self.rpm_value, self.rpm_mod]
            }
        
        for item in columns:
            if self.no_dp > len(val_dict[item][0]):
                dp_range = len(val_dict[item][0])
            else:
                dp_range = self.no_dp
                
            for i in range(dp_range):
                val_dict[item][1].append(val_dict[item][0][i])

        return self.datetime_mod, self.bpos_mod, self.woh_mod, self.torq_mod, self.spp_mod, self.depth_mod, self.flow_in_mod, self.rpm_mod    
        
    def show_graph2(self):
        from pylive_mod import live_plotter

        self.open_file()
        self.convert_dataframe()
        self.deliver_values(no_dp = 100000, columns = ['datetime', 'depth', 'bpos', 'woh'])

        fst_p = 0
        size = 300 # density of points in the graph (100 by default)
        
        x_vec = self.datetime_mod[fst_p:size]
        y_vec = self.depth_mod[fst_p:size]
        y2_vec = self.bpos_mod[fst_p:size]
        y3_vec = self.woh_mod[fst_p:size]
        line1 = []
        line2 = []
        line3 = []
        
        for i in range(self.no_dp):
            #print(self.datetime_mod[i:6+i])
            #print('Ostatni element y_vec: ', y_vec[-1])
            #print(x_vec)
            x_vec[-1] = self.datetime_mod[size+i]
            y_vec[-1] = self.depth_mod[size+i]
            y2_vec[-1] = self.bpos_mod[size+i]
            y3_vec[-1] = self.woh_mod[size+i]
            
            line1, line2, line3 = live_plotter(x_vec, y_vec, y2_vec, y3_vec, line1, line2, line3)

            x_vec = np.append(x_vec[1:], 0.0)
            y_vec = np.append(y_vec[1:], 0.0)
            y2_vec = np.append(y2_vec[1:], 0.0)
            y3_vec = np.append(y3_vec[1:], 0.0)

def main():
    Graph = Visualizer()
    Graph.open_file() #Opens the streamed file
    Graph.convert_dataframe() #Converts dataframe to readable format
    Graph.show_graph2()

#Show us the graph
#main()
def live_plotter(x_data, y1_data, y2_data, y3_data, line1, line2, line3, identifier='',pause_time=1):
if line1 == [] and line2 == [] and line3 == []:
    # this is the call to matplotlib that allows dynamic plotting
    plt.ion()
    #fig = Figure(figsize = (5, 4), dpi = 100)
    #host = fig.add_subplot()
    fig, host = plt.subplots()
    fig.set_figheight(7) #adjust figure's height
    fig.set_figwidth(14) #adjust figure's width
    fig.subplots_adjust(0.15)

    #Line1
    #line1 = host
    ln1 = host
    ln2 = host.twinx()
    ln3 = host.twinx()

    ln2.spines['right'].set_position(('axes', 1.))
    ln3.spines['right'].set_position(('axes', 1.12))
    make_patch_spines_invisible(ln2)
    make_patch_spines_invisible(ln3)
    ln2.spines['right'].set_visible(True)
    ln3.spines['right'].set_visible(True)              
    
    ln1.set_xlabel('Date & Time') #main x axis
    ln1.set_ylabel('Depth') #left y axis
    ln2.set_ylabel('Elevator Height')
    ln3.set_ylabel('Weight on Hook')

    #
    x_formatter = FixedFormatter([x_data])
    x_locator = FixedLocator([x_data[5]])

    ln1.xaxis.set_major_formatter(x_formatter)
    ln1.xaxis.set_major_locator(x_locator)
    #
    
    ln1.locator_params(nbins = 5, axis = 'y')
    ln1.tick_params(axis='x', rotation=90) #rotates x ticks 90 degrees down

    ln2.axes.set_ylim(0, 30)
    ln3.axes.set_ylim(200, 250)
    
    line1, = ln1.plot(x_data, y1_data, color = 'black', linestyle = 'solid', alpha=0.8, label = 'Depth')
    line2, = ln2.plot(x_data, y2_data, color = 'blue', linestyle = 'dashed', alpha=0.8, label = 'Elevator Height')
    line3, = ln3.plot(x_data, y3_data, color = 'red', linestyle = 'solid', alpha=0.8, label = 'Weight on Hook')
    
    # ----- embedding -----
    canvas = FigureCanvasTkAgg(fig, master = root)
    canvas.draw()
    
    # placing the canvas on the Tkinter window 
    canvas.get_tk_widget().pack() 

    # creating the Matplotlib toolbar 
    toolbar = NavigationToolbar2Tk(canvas, root) 
    toolbar.update() 

    # placing the toolbar on the Tkinter window 
    canvas.get_tk_widget().pack() 
    #----- -----
    
    plt.title('WiTSML Visualizer')
    fig.tight_layout() #the graphs is not clipped on sides

    #Shows legend
    lines = [line1, line2, line3]
    host.legend(lines, [l.get_label() for l in lines], loc = 'lower left')

    #Shows grid
    plt.grid(True)

    #Shows the whole graph
    plt.show()

# after the figure, axis, and line are created, we only need to update the y-data
mod_x_data = convert_x_data(x_data, 10)
line1.axes.set_xticklabels(mod_x_data)
line1.set_ydata(y1_data)
line2.set_ydata(y2_data)
line3.set_ydata(y3_data)


#Debugging
#rint('plt.lim: ', ln2.axes.get_ylim())

# adjust limits if new data goes beyond bounds
# limit for line 1
if np.min(y1_data)<=line1.axes.get_ylim()[0] or np.max(y1_data)>=line1.axes.get_ylim()[1]:
    plt.ylim(0, 10)
    line1.axes.set_ylim([np.min(y1_data)-np.std(y1_data),np.max(y1_data)+np.std(y1_data)])

# limit for line 2
if np.min(y2_data)<=line2.axes.get_ylim()[0] or np.max(y2_data)>=line2.axes.get_ylim()[1]:
    plt.ylim([np.min(y2_data)-np.std(y2_data),np.max(y2_data)+np.std(y2_data)])
    #plt.ylim(0, 25)

# limit for line 3
if np.min(y3_data)<=line3.axes.get_ylim()[0] or np.max(y3_data)>=line3.axes.get_ylim()[1]:
    plt.ylim([np.min(y3_data)-np.std(y3_data),np.max(y3_data)+np.std(y3_data)])
    #plt.ylim(0, 25)

# Adds lines to the legend
#host.legend(lines, [l.get_label() for l in lines])
# this pauses the data so the figure/axis can catch up - the amount of pause can be altered above
plt.pause(pause_time)

# return line so we can update it again in the next iteration
return line1, line2, line3
可视化工具:

    # -*- coding: utf-8 -*-
"""
Created on Tue Oct  6 10:24:35 2020

@author: Dar0
"""

from tkinter import * #import tkinter module
from visualizer import main #import module 'visualizer' that shows the graph in real time

class Application(Frame):
    ''' Interface for visualizing graphs, indicators and text-box. '''
    def __init__(self, master):
        super(Application, self).__init__(master)
        self.grid()
        self.create_widgets()
    
    def create_widgets(self):
        # Label of the 1st graph
        Label(self,
              text='Hook Load / Elevator Height / Depth vs Time'
              ).grid(row = 0, column = 0, sticky = W)
        
        # Graph 1 - Hook Load / Elevator Height / Depth vs Time
        # button that displays the plot 
        plot_button = Button(self,
                             master = root,
                             command = main,
                             height = 2, 
                             width = 10, 
                             text = "Plot").grid(row = 1, column = 0, sticky = W)

        # place the button 
        # in main window 
        
        # Label of the 2nd graph
        Label(self,
              text = 'Hook Load / Elevator Height vs Time'
              ).grid(row = 2, column = 0, sticky = W)
        
        # Graph 2 - Hook Load / Elevator Height vs Time
        
        #Label of the 3rd graph
        Label(self,
              text = 'Hook Load vs Time'
              ).grid(row = 4, column = 0, sticky = W)
        
        #Graph 3 - Hook Load vs Time
        
        #Label of the 1st indicator
        Label(self,
              text = '1st performance indicator'
              ).grid(row = 0, column = 1, sticky = W)
        
        #1st performance indicator
        
        #Label of 2nd performance indicator
        Label(self,
              text = '2nd performance indicator'
              ).grid(row = 2, column = 1, sticky = W)
        
        #2nd performance indicator
        
        #Label of 3rd performance indicator
        Label(self,
              text = '3rd performance indicator'
              ).grid(row = 4, column = 1, sticky = W)
        
        #Text-box showing comments based on received data
        self.text_box = Text(self, width = 50, height = 10, wrap = WORD)
        self.text_box.grid(row = 6, column = 0, columnspan = 1)
        self.text_box.delete(0.0, END)
        self.text_box.insert(0.0, 'My message will be here.')
        
#Main part
root = Tk()
root.title('WiTSML Visualizer by Dar0')
app = Application(root)
root.mainloop()
#WiTSML visualizer
#Created by Dariusz Krol
#import matplotlib
#matplotlib.use('TkAgg')
#from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
#from matplotlib.figure import Figure

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

class Visualizer(object):
    """ Includes all the methods needed to show streamed data. """
    def __init__(self):
        self.file_path = 'C:/Anaconda/_my_files/witsml_reader/modified_witsml.csv' #Defines which file is streamed

        self.datetime_mod = []
        self.bpos_mod = []
        self.woh_mod = []
        self.torq_mod = []
        self.spp_mod = []
        self.depth_mod = []
        self.flow_in_mod = []
        self.rpm_mod = []

    def open_file(self):
        self.df = pd.read_csv(self.file_path, low_memory = False, nrows = 300000) #Opens the STREAMED file (already modified so that data convert is not required)
        self.df = self.df.drop(0)
        self.df = pd.DataFrame(self.df)

        return self.df

    def convert_dataframe(self):
        self.df = self.df.values.T.tolist() #Do transposition of the dataframe and convert to list
        #Columns are as following:
        # - DATETIME
        # - BPOS
        # - WOH
        # - TORQ
        # - SPP
        # - DEPTH
        # - FLOW_IN
        # - RPM
        self.datetime_value = self.df[0]
        self.bpos_value = self.df[1]
        self.woh_value = self.df[2]
        self.torq_value = self.df[3]
        self.spp_value = self.df[4]
        self.depth_value = self.df[5]
        self.flow_in_value = self.df[5]
        self.rpm_value = self.df[7]

        return self.datetime_value, self.bpos_value, self.woh_value, self.torq_value, self.spp_value, self.depth_value, self.flow_in_value, self.rpm_value
        #print(self.bpos_value)

    def deliver_values(self, no_dp, columns):
        ''' Method gets no_dp amount of data points from the original file. '''
        self.no_dp = no_dp #defines how many data points will be presented in the graph

        val_dict = {
            'datetime': [self.datetime_value, self.datetime_mod],
            'bpos': [self.bpos_value, self.bpos_mod],
            'woh': [self.woh_value, self.woh_mod],
            'torq': [self.torq_value, self.torq_mod],
            'spp': [self.spp_value, self.spp_mod],
            'depth': [self.depth_value, self.depth_mod],
            'flow_in': [self.flow_in_value, self.flow_in_mod],
            'rpm': [self.rpm_value, self.rpm_mod]
            }
        
        for item in columns:
            if self.no_dp > len(val_dict[item][0]):
                dp_range = len(val_dict[item][0])
            else:
                dp_range = self.no_dp
                
            for i in range(dp_range):
                val_dict[item][1].append(val_dict[item][0][i])

        return self.datetime_mod, self.bpos_mod, self.woh_mod, self.torq_mod, self.spp_mod, self.depth_mod, self.flow_in_mod, self.rpm_mod    
        
    def show_graph2(self):
        from pylive_mod import live_plotter

        self.open_file()
        self.convert_dataframe()
        self.deliver_values(no_dp = 100000, columns = ['datetime', 'depth', 'bpos', 'woh'])

        fst_p = 0
        size = 300 # density of points in the graph (100 by default)
        
        x_vec = self.datetime_mod[fst_p:size]
        y_vec = self.depth_mod[fst_p:size]
        y2_vec = self.bpos_mod[fst_p:size]
        y3_vec = self.woh_mod[fst_p:size]
        line1 = []
        line2 = []
        line3 = []
        
        for i in range(self.no_dp):
            #print(self.datetime_mod[i:6+i])
            #print('Ostatni element y_vec: ', y_vec[-1])
            #print(x_vec)
            x_vec[-1] = self.datetime_mod[size+i]
            y_vec[-1] = self.depth_mod[size+i]
            y2_vec[-1] = self.bpos_mod[size+i]
            y3_vec[-1] = self.woh_mod[size+i]
            
            line1, line2, line3 = live_plotter(x_vec, y_vec, y2_vec, y3_vec, line1, line2, line3)

            x_vec = np.append(x_vec[1:], 0.0)
            y_vec = np.append(y_vec[1:], 0.0)
            y2_vec = np.append(y2_vec[1:], 0.0)
            y3_vec = np.append(y3_vec[1:], 0.0)

def main():
    Graph = Visualizer()
    Graph.open_file() #Opens the streamed file
    Graph.convert_dataframe() #Converts dataframe to readable format
    Graph.show_graph2()

#Show us the graph
#main()
def live_plotter(x_data, y1_data, y2_data, y3_data, line1, line2, line3, identifier='',pause_time=1):
if line1 == [] and line2 == [] and line3 == []:
    # this is the call to matplotlib that allows dynamic plotting
    plt.ion()
    #fig = Figure(figsize = (5, 4), dpi = 100)
    #host = fig.add_subplot()
    fig, host = plt.subplots()
    fig.set_figheight(7) #adjust figure's height
    fig.set_figwidth(14) #adjust figure's width
    fig.subplots_adjust(0.15)

    #Line1
    #line1 = host
    ln1 = host
    ln2 = host.twinx()
    ln3 = host.twinx()

    ln2.spines['right'].set_position(('axes', 1.))
    ln3.spines['right'].set_position(('axes', 1.12))
    make_patch_spines_invisible(ln2)
    make_patch_spines_invisible(ln3)
    ln2.spines['right'].set_visible(True)
    ln3.spines['right'].set_visible(True)              
    
    ln1.set_xlabel('Date & Time') #main x axis
    ln1.set_ylabel('Depth') #left y axis
    ln2.set_ylabel('Elevator Height')
    ln3.set_ylabel('Weight on Hook')

    #
    x_formatter = FixedFormatter([x_data])
    x_locator = FixedLocator([x_data[5]])

    ln1.xaxis.set_major_formatter(x_formatter)
    ln1.xaxis.set_major_locator(x_locator)
    #
    
    ln1.locator_params(nbins = 5, axis = 'y')
    ln1.tick_params(axis='x', rotation=90) #rotates x ticks 90 degrees down

    ln2.axes.set_ylim(0, 30)
    ln3.axes.set_ylim(200, 250)
    
    line1, = ln1.plot(x_data, y1_data, color = 'black', linestyle = 'solid', alpha=0.8, label = 'Depth')
    line2, = ln2.plot(x_data, y2_data, color = 'blue', linestyle = 'dashed', alpha=0.8, label = 'Elevator Height')
    line3, = ln3.plot(x_data, y3_data, color = 'red', linestyle = 'solid', alpha=0.8, label = 'Weight on Hook')
    
    # ----- embedding -----
    canvas = FigureCanvasTkAgg(fig, master = root)
    canvas.draw()
    
    # placing the canvas on the Tkinter window 
    canvas.get_tk_widget().pack() 

    # creating the Matplotlib toolbar 
    toolbar = NavigationToolbar2Tk(canvas, root) 
    toolbar.update() 

    # placing the toolbar on the Tkinter window 
    canvas.get_tk_widget().pack() 
    #----- -----
    
    plt.title('WiTSML Visualizer')
    fig.tight_layout() #the graphs is not clipped on sides

    #Shows legend
    lines = [line1, line2, line3]
    host.legend(lines, [l.get_label() for l in lines], loc = 'lower left')

    #Shows grid
    plt.grid(True)

    #Shows the whole graph
    plt.show()

# after the figure, axis, and line are created, we only need to update the y-data
mod_x_data = convert_x_data(x_data, 10)
line1.axes.set_xticklabels(mod_x_data)
line1.set_ydata(y1_data)
line2.set_ydata(y2_data)
line3.set_ydata(y3_data)


#Debugging
#rint('plt.lim: ', ln2.axes.get_ylim())

# adjust limits if new data goes beyond bounds
# limit for line 1
if np.min(y1_data)<=line1.axes.get_ylim()[0] or np.max(y1_data)>=line1.axes.get_ylim()[1]:
    plt.ylim(0, 10)
    line1.axes.set_ylim([np.min(y1_data)-np.std(y1_data),np.max(y1_data)+np.std(y1_data)])

# limit for line 2
if np.min(y2_data)<=line2.axes.get_ylim()[0] or np.max(y2_data)>=line2.axes.get_ylim()[1]:
    plt.ylim([np.min(y2_data)-np.std(y2_data),np.max(y2_data)+np.std(y2_data)])
    #plt.ylim(0, 25)

# limit for line 3
if np.min(y3_data)<=line3.axes.get_ylim()[0] or np.max(y3_data)>=line3.axes.get_ylim()[1]:
    plt.ylim([np.min(y3_data)-np.std(y3_data),np.max(y3_data)+np.std(y3_data)])
    #plt.ylim(0, 25)

# Adds lines to the legend
#host.legend(lines, [l.get_label() for l in lines])
# this pauses the data so the figure/axis can catch up - the amount of pause can be altered above
plt.pause(pause_time)

# return line so we can update it again in the next iteration
return line1, line2, line3
pylive\u mod(实时绘图仪):

    # -*- coding: utf-8 -*-
"""
Created on Tue Oct  6 10:24:35 2020

@author: Dar0
"""

from tkinter import * #import tkinter module
from visualizer import main #import module 'visualizer' that shows the graph in real time

class Application(Frame):
    ''' Interface for visualizing graphs, indicators and text-box. '''
    def __init__(self, master):
        super(Application, self).__init__(master)
        self.grid()
        self.create_widgets()
    
    def create_widgets(self):
        # Label of the 1st graph
        Label(self,
              text='Hook Load / Elevator Height / Depth vs Time'
              ).grid(row = 0, column = 0, sticky = W)
        
        # Graph 1 - Hook Load / Elevator Height / Depth vs Time
        # button that displays the plot 
        plot_button = Button(self,
                             master = root,
                             command = main,
                             height = 2, 
                             width = 10, 
                             text = "Plot").grid(row = 1, column = 0, sticky = W)

        # place the button 
        # in main window 
        
        # Label of the 2nd graph
        Label(self,
              text = 'Hook Load / Elevator Height vs Time'
              ).grid(row = 2, column = 0, sticky = W)
        
        # Graph 2 - Hook Load / Elevator Height vs Time
        
        #Label of the 3rd graph
        Label(self,
              text = 'Hook Load vs Time'
              ).grid(row = 4, column = 0, sticky = W)
        
        #Graph 3 - Hook Load vs Time
        
        #Label of the 1st indicator
        Label(self,
              text = '1st performance indicator'
              ).grid(row = 0, column = 1, sticky = W)
        
        #1st performance indicator
        
        #Label of 2nd performance indicator
        Label(self,
              text = '2nd performance indicator'
              ).grid(row = 2, column = 1, sticky = W)
        
        #2nd performance indicator
        
        #Label of 3rd performance indicator
        Label(self,
              text = '3rd performance indicator'
              ).grid(row = 4, column = 1, sticky = W)
        
        #Text-box showing comments based on received data
        self.text_box = Text(self, width = 50, height = 10, wrap = WORD)
        self.text_box.grid(row = 6, column = 0, columnspan = 1)
        self.text_box.delete(0.0, END)
        self.text_box.insert(0.0, 'My message will be here.')
        
#Main part
root = Tk()
root.title('WiTSML Visualizer by Dar0')
app = Application(root)
root.mainloop()
#WiTSML visualizer
#Created by Dariusz Krol
#import matplotlib
#matplotlib.use('TkAgg')
#from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
#from matplotlib.figure import Figure

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

class Visualizer(object):
    """ Includes all the methods needed to show streamed data. """
    def __init__(self):
        self.file_path = 'C:/Anaconda/_my_files/witsml_reader/modified_witsml.csv' #Defines which file is streamed

        self.datetime_mod = []
        self.bpos_mod = []
        self.woh_mod = []
        self.torq_mod = []
        self.spp_mod = []
        self.depth_mod = []
        self.flow_in_mod = []
        self.rpm_mod = []

    def open_file(self):
        self.df = pd.read_csv(self.file_path, low_memory = False, nrows = 300000) #Opens the STREAMED file (already modified so that data convert is not required)
        self.df = self.df.drop(0)
        self.df = pd.DataFrame(self.df)

        return self.df

    def convert_dataframe(self):
        self.df = self.df.values.T.tolist() #Do transposition of the dataframe and convert to list
        #Columns are as following:
        # - DATETIME
        # - BPOS
        # - WOH
        # - TORQ
        # - SPP
        # - DEPTH
        # - FLOW_IN
        # - RPM
        self.datetime_value = self.df[0]
        self.bpos_value = self.df[1]
        self.woh_value = self.df[2]
        self.torq_value = self.df[3]
        self.spp_value = self.df[4]
        self.depth_value = self.df[5]
        self.flow_in_value = self.df[5]
        self.rpm_value = self.df[7]

        return self.datetime_value, self.bpos_value, self.woh_value, self.torq_value, self.spp_value, self.depth_value, self.flow_in_value, self.rpm_value
        #print(self.bpos_value)

    def deliver_values(self, no_dp, columns):
        ''' Method gets no_dp amount of data points from the original file. '''
        self.no_dp = no_dp #defines how many data points will be presented in the graph

        val_dict = {
            'datetime': [self.datetime_value, self.datetime_mod],
            'bpos': [self.bpos_value, self.bpos_mod],
            'woh': [self.woh_value, self.woh_mod],
            'torq': [self.torq_value, self.torq_mod],
            'spp': [self.spp_value, self.spp_mod],
            'depth': [self.depth_value, self.depth_mod],
            'flow_in': [self.flow_in_value, self.flow_in_mod],
            'rpm': [self.rpm_value, self.rpm_mod]
            }
        
        for item in columns:
            if self.no_dp > len(val_dict[item][0]):
                dp_range = len(val_dict[item][0])
            else:
                dp_range = self.no_dp
                
            for i in range(dp_range):
                val_dict[item][1].append(val_dict[item][0][i])

        return self.datetime_mod, self.bpos_mod, self.woh_mod, self.torq_mod, self.spp_mod, self.depth_mod, self.flow_in_mod, self.rpm_mod    
        
    def show_graph2(self):
        from pylive_mod import live_plotter

        self.open_file()
        self.convert_dataframe()
        self.deliver_values(no_dp = 100000, columns = ['datetime', 'depth', 'bpos', 'woh'])

        fst_p = 0
        size = 300 # density of points in the graph (100 by default)
        
        x_vec = self.datetime_mod[fst_p:size]
        y_vec = self.depth_mod[fst_p:size]
        y2_vec = self.bpos_mod[fst_p:size]
        y3_vec = self.woh_mod[fst_p:size]
        line1 = []
        line2 = []
        line3 = []
        
        for i in range(self.no_dp):
            #print(self.datetime_mod[i:6+i])
            #print('Ostatni element y_vec: ', y_vec[-1])
            #print(x_vec)
            x_vec[-1] = self.datetime_mod[size+i]
            y_vec[-1] = self.depth_mod[size+i]
            y2_vec[-1] = self.bpos_mod[size+i]
            y3_vec[-1] = self.woh_mod[size+i]
            
            line1, line2, line3 = live_plotter(x_vec, y_vec, y2_vec, y3_vec, line1, line2, line3)

            x_vec = np.append(x_vec[1:], 0.0)
            y_vec = np.append(y_vec[1:], 0.0)
            y2_vec = np.append(y2_vec[1:], 0.0)
            y3_vec = np.append(y3_vec[1:], 0.0)

def main():
    Graph = Visualizer()
    Graph.open_file() #Opens the streamed file
    Graph.convert_dataframe() #Converts dataframe to readable format
    Graph.show_graph2()

#Show us the graph
#main()
def live_plotter(x_data, y1_data, y2_data, y3_data, line1, line2, line3, identifier='',pause_time=1):
if line1 == [] and line2 == [] and line3 == []:
    # this is the call to matplotlib that allows dynamic plotting
    plt.ion()
    #fig = Figure(figsize = (5, 4), dpi = 100)
    #host = fig.add_subplot()
    fig, host = plt.subplots()
    fig.set_figheight(7) #adjust figure's height
    fig.set_figwidth(14) #adjust figure's width
    fig.subplots_adjust(0.15)

    #Line1
    #line1 = host
    ln1 = host
    ln2 = host.twinx()
    ln3 = host.twinx()

    ln2.spines['right'].set_position(('axes', 1.))
    ln3.spines['right'].set_position(('axes', 1.12))
    make_patch_spines_invisible(ln2)
    make_patch_spines_invisible(ln3)
    ln2.spines['right'].set_visible(True)
    ln3.spines['right'].set_visible(True)              
    
    ln1.set_xlabel('Date & Time') #main x axis
    ln1.set_ylabel('Depth') #left y axis
    ln2.set_ylabel('Elevator Height')
    ln3.set_ylabel('Weight on Hook')

    #
    x_formatter = FixedFormatter([x_data])
    x_locator = FixedLocator([x_data[5]])

    ln1.xaxis.set_major_formatter(x_formatter)
    ln1.xaxis.set_major_locator(x_locator)
    #
    
    ln1.locator_params(nbins = 5, axis = 'y')
    ln1.tick_params(axis='x', rotation=90) #rotates x ticks 90 degrees down

    ln2.axes.set_ylim(0, 30)
    ln3.axes.set_ylim(200, 250)
    
    line1, = ln1.plot(x_data, y1_data, color = 'black', linestyle = 'solid', alpha=0.8, label = 'Depth')
    line2, = ln2.plot(x_data, y2_data, color = 'blue', linestyle = 'dashed', alpha=0.8, label = 'Elevator Height')
    line3, = ln3.plot(x_data, y3_data, color = 'red', linestyle = 'solid', alpha=0.8, label = 'Weight on Hook')
    
    # ----- embedding -----
    canvas = FigureCanvasTkAgg(fig, master = root)
    canvas.draw()
    
    # placing the canvas on the Tkinter window 
    canvas.get_tk_widget().pack() 

    # creating the Matplotlib toolbar 
    toolbar = NavigationToolbar2Tk(canvas, root) 
    toolbar.update() 

    # placing the toolbar on the Tkinter window 
    canvas.get_tk_widget().pack() 
    #----- -----
    
    plt.title('WiTSML Visualizer')
    fig.tight_layout() #the graphs is not clipped on sides

    #Shows legend
    lines = [line1, line2, line3]
    host.legend(lines, [l.get_label() for l in lines], loc = 'lower left')

    #Shows grid
    plt.grid(True)

    #Shows the whole graph
    plt.show()

# after the figure, axis, and line are created, we only need to update the y-data
mod_x_data = convert_x_data(x_data, 10)
line1.axes.set_xticklabels(mod_x_data)
line1.set_ydata(y1_data)
line2.set_ydata(y2_data)
line3.set_ydata(y3_data)


#Debugging
#rint('plt.lim: ', ln2.axes.get_ylim())

# adjust limits if new data goes beyond bounds
# limit for line 1
if np.min(y1_data)<=line1.axes.get_ylim()[0] or np.max(y1_data)>=line1.axes.get_ylim()[1]:
    plt.ylim(0, 10)
    line1.axes.set_ylim([np.min(y1_data)-np.std(y1_data),np.max(y1_data)+np.std(y1_data)])

# limit for line 2
if np.min(y2_data)<=line2.axes.get_ylim()[0] or np.max(y2_data)>=line2.axes.get_ylim()[1]:
    plt.ylim([np.min(y2_data)-np.std(y2_data),np.max(y2_data)+np.std(y2_data)])
    #plt.ylim(0, 25)

# limit for line 3
if np.min(y3_data)<=line3.axes.get_ylim()[0] or np.max(y3_data)>=line3.axes.get_ylim()[1]:
    plt.ylim([np.min(y3_data)-np.std(y3_data),np.max(y3_data)+np.std(y3_data)])
    #plt.ylim(0, 25)

# Adds lines to the legend
#host.legend(lines, [l.get_label() for l in lines])
# this pauses the data so the figure/axis can catch up - the amount of pause can be altered above
plt.pause(pause_time)

# return line so we can update it again in the next iteration
return line1, line2, line3
def live_绘图仪(x_数据、y1_数据、y2_数据、y3_数据、第1行、第2行、第3行,标识符=“”,暂停时间=1):
如果第1行==[]和第2行==[]和第3行==[]:
#这是对matplotlib的调用,允许动态打印
plt.ion()
#图=图(figsize=(5,4),dpi=100)
#主机=图添加_子批次()
图,主机=plt.subplot()
图:设置figheight(7)#调整人物高度
图设置图宽(14)#调整图宽
图子批次调整(0.15)
#第1行
#line1=主机
ln1=主机
ln2=host.twinx()
ln3=host.twinx()
ln2.脊椎['right']设置位置(('axes',1.))
ln3.脊椎[‘右’]。设置位置((‘轴’,1.12))
使_面片_刺_不可见(ln2)
使_补丁_刺_不可见(ln3)
ln2.脊椎['右'].设置为可见(真)
ln3.脊椎['right'].set_可见(真)
ln1.设置标签(“日期和时间”)#主x轴
ln1.设置_ylabel('Depth')#左y轴
ln2.设置标签(“电梯高度”)
ln3.设置标签(“吊钩上的重量”)
#
x_格式化程序=固定格式化程序([x_数据])
x_定位器=固定定位器([x_数据[5]])
ln1.xaxis.set_major_格式化程序(x_格式化程序)
ln1.xaxis.set_major_定位器(x_定位器)
#
ln1.定位器参数(nbins=5,轴='y')
ln1.勾号参数(轴=x',旋转=90)#将x勾号向下旋转90度
ln2.轴设置Y(0,30)
ln3.轴设置长度(200250)
line1,=ln1.绘图(x_数据,y1_数据,颜色='黑色',线型='实心',alpha=0.8,标签='深度')
line2,=ln2.绘图(x_数据,y2_数据,颜色='蓝色',线型='虚线',alpha=0.8,标签='电梯高度')
line3,=ln3.plot(x_数据,y3_数据,颜色='红色',线型='实心',alpha=0.8,标签='挂钩上的重量')
#----嵌入-----
canvas=FigureCanvasTkAgg(图,主控=根)
canvas.draw()
#将画布放置在Tkinter窗口上
canvas.get_tk_widget().pack()
#创建Matplotlib工具栏
工具栏=导航工具栏2TK(画布,根)
toolbar.update()
#将工具栏放置在Tkinter窗口上
canvas.get_tk_widget().pack()
#----- -----
产品名称(“WiTSML可视化工具”)
图紧_布局()#图形未剪裁在侧面
#显示图例
行=[line1,line2,line3]
图例(行,[l.get_label()表示行中的l],loc='lower left')
#显示网格
plt.grid(真)
#显示整个图表
plt.show()
#创建图形、轴和线之后,我们只需要更新y数据
mod_x_data=转换_x_数据(x_数据,10)
line1.轴.设置x刻度线(mod_x_数据)
第1行。设置数据(y1数据)
第2行。设置数据(y2数据)
第3行。设置数据(y3数据)
#调试
#rint('plt.lim:',ln2.axes.get_ylim())
#如果新数据超出范围,则调整限制
#1号线的限制
如果np.min(y1_数据)=line1.axes.get_ylim()[1]:
plt.ylim(0,10)
行1.轴设置Y轴([np.min(y1_数据)-np.std(y1_数据),np.max(y1_数据)+np.std(y1_数据)])
#2号线的限制
如果np.min(y2_数据)=line2.axes.get_ylim()[1]:
plt.ylim([np.min(y2_数据)-np.std(y2_数据),np.max(y2_数据)+np.std(y2_数据)])
#plt.ylim(0,25)
#3号线的限制
如果np.min(y3_数据)=line3.axes.get_ylim()[1]:
plt.ylim([np.min(y3_数据)-np.std(y3_数据),np.max(y3_数据)+np.std(y3_数据)])
#plt.ylim(0,25)
#向图例中添加线条
#图例(行,[l.get_label()表示l行中的l])
#这会暂停数据,以便图形/轴可以跟上-暂停的数量可以在上面更改
plt.暂停(暂停时间)
#返回行,以便我们可以在下一次迭代中再次更新它
返回行1、行2、行3
绘图按钮=按钮(self,master=root,…)
应该是导致错误的行。正如错误所说,您指定了两个主机:
self
master=root
。我认为您需要删除
master=root