在一个 Python Tkinter GUI 中嵌入多个实时图形

Embedding multiple real-time graphs in one Python Tkinter GUI

我是 Tkinter 的新手。我正在尝试在 window 中绘制两个实时动画图形,但是两个实时数据在一段时间后重叠到同一个图形上。我希望它们显示在单独的图表上。 I put a gif to show my output。 我想将其他数据绘制到左图中。有没有什么办法解决这一问题?如果我能做到,我会尝试绘制三张图而不是两张。你能帮我看看下面的代码吗?

from matplotlib.backends.backend_tkagg import (
    FigureCanvasTkAgg, NavigationToolbar2Tk)
import tkinter as Tk
from matplotlib.figure import Figure
import random
from itertools import count
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import numpy as np
from pandas import DataFrame

plt.style.use('fivethirtyeight')
# values for first graph
x_vals = []
y_vals = []
# values for second graph
x_vals2 = []
y_vals2 = []

index = count()
index2 = count()


def animate(i):
    x_vals.append(next(index))
    y_vals.append(random.randint(0, 5))
    plt.cla()  # clear the current axes
    plt.plot(x_vals, y_vals)


def animate2(j):
    x_vals2.append(next(index2))
    y_vals2.append(random.randint(0, 5))
    plt.cla()  # clear the current axes
    plt.plot(x_vals2, y_vals2)


# GUI

root = Tk.Tk()
label = Tk.Label(root, text="Realtime Animated Graphs").grid(column=0, row=0)

# graph 1
canvas = FigureCanvasTkAgg(plt.gcf(), master=root)
canvas.get_tk_widget().grid(column=0, row=1)
ani = FuncAnimation(plt.gcf(), animate, interval=1000, blit=False)

# graph 2
canvas2 = FigureCanvasTkAgg(plt.gcf(), master=root)
canvas2.get_tk_widget().grid(column=1, row=1)
ax2 = plt.gcf().add_subplot(111)
line2, = ax2.plot(x_vals2, y_vals2)
ani2 = FuncAnimation(plt.gcf(), animate2, interval=1000, blit=False)

Tk.mainloop()



如果你不是特别需要canvas1和2,你可以为一个图创建两个子图/canvas.
然后你会得到 2 个轴:ax1ax2.

您只能使用一个 FuncAnimation 和相同的 x。 如果您需要 ax1ax2 的单独动画,您也可以这样做,只需更新相应动画中的 ax1ax2

这是代码片段:

import random
import tkinter as Tk
from itertools import count

import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

plt.style.use('fivethirtyeight')
# values for first graph
x_vals = []
y_vals = []
# values for second graph
y_vals2 = []

index = count()
index2 = count()

def animate(i):
    # Generate values
    x_vals.append(next(index))
    y_vals.append(random.randint(0, 5))
    y_vals2.append(random.randint(0, 5))
    # Get all axes of figure
    ax1, ax2 = plt.gcf().get_axes()
    # Clear current data
    ax1.cla()
    ax2.cla()
    # Plot new data
    ax1.plot(x_vals, y_vals)
    ax2.plot(x_vals, y_vals2)


# GUI
root = Tk.Tk()
label = Tk.Label(root, text="Realtime Animated Graphs").grid(column=0, row=0)

# graph 1
canvas = FigureCanvasTkAgg(plt.gcf(), master=root)
canvas.get_tk_widget().grid(column=0, row=1)
# Create two subplots in row 1 and column 1, 2
plt.gcf().subplots(1, 2)
ani = FuncAnimation(plt.gcf(), animate, interval=1000, blit=False)

Tk.mainloop()

这是输出: