在matplotlib子图中删除图线

4c8rllxm  于 2023-05-23  发布在  其他
关注(0)|答案(1)|浏览(166)

我正在使用matplotlib和python以及tkinter。我的图表绘制了3条线。下面是相关代码:

fig = plt.Figure(figsize=(8, 6), dpi=92)
    canvas = FigureCanvasTkAgg(fig, master=root)  # A tk.DrawingArea.
    canvas.get_tk_widget().grid(row=2, column=3, columnspan=2, rowspan=2)
    plot1 = fig.add_subplot(111)
    plot1.set_ylim(40, 210)
    plot2 = plot1.twinx()
    sysline = plot1.plot(listDateTime, listSystolic, color='orange', label = "Systolic", linewidth=2, linestyle='solid')
    dialine = plot1.plot(listDateTime, listDiastolic, color='red', label = "Diastolic", linewidth=2, linestyle='solid')
    weightline = plot2.plot(listDateTime, listWeight, color='blue', label = "Weight", linewidth=2, linestyle='dotted')
    plot2.set_ylim(160, 220)
    for label in plot1.xaxis.get_ticklabels():
        label.set_rotation(-90)
    plot1.xaxis.set_major_formatter(ticker.FuncFormatter(getDateString))
    plot1.set_xlabel("Test Date")
    plot1.set_ylabel("Pressure (mmHg)")
    plot2.set_ylabel("Weight (lbs)")
    plot1.set_title(graphTitle)
    plot1.legend(loc='upper left')
    plot2.legend(loc='upper right')
    plot1.grid(True)
#    plot1.set_autoscale_on(True)
#    plot2.set_autoscale_on(True)
    plt.tight_layout()
    canvas.draw()

当我以交互方式加载更新的数据集时,新的线会覆盖旧的线,我更愿意删除旧的线并重新绘制数据。
因为它在子情节上,所以这种方法不起作用:line1 = plot1.pop(0) line1.remove() line2 = plot2.pop(0) line2.remove()
我尝试获取这些行的句柄并使用.remove(),这不会引发错误。但也没有任何效果。
.remove()在重新绘制图形之前不会发生吗?我错过了什么?

mctunoxg

mctunoxg1#

您的不完整示例无法替换/删除图中前面的行,因为您没有使用plot1.clear()plot2.clear()
有关详细信息,请参阅此问题:Clearing a subplot in Matplotlib
现在,假设你这样做是为了制作一个“交互式”的情节,这里有一个工作POC:

import tkinter as tk
from tkinter import messagebox
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import matplotlib.pyplot as plt

def update_plot():
    data = entry.get()
    values = [float(val) for val in data.split(',')]
    n = len(values)
    try:
        x = [i * 10 / (n - 1) for i in range(n)]
    except ZeroDivisionError:
        messagebox.showerror("error", "Using less than two values won't work")
        return  # trick to prevent the Zero Division error

    y = values

    # This is what replace the previous lines with newer ones
    plot1.clear()
    plot2.clear()

    # Plotting new random lines
    plot1.plot(x, y, color='orange', label="random line 1", linewidth=2, linestyle='solid')
    plot1.plot(x, [val * 0.8 for val in y], color='red', label="random line 2", linewidth=2, linestyle='solid')
    plot2.plot(x, [val * 2 for val in y], color='blue', label="random line 3", linewidth=2, linestyle='dotted')

    # Setting plot properties and redrawing the canvas
    plot1.set_ylim(0, max(y) + 1)
    plot2.set_ylim(0, max(y) * 2 + 1)
    plot1.set_xlabel("X")
    plot1.set_ylabel("Y1")
    plot2.set_ylabel("Y2")
    plot1.set_title("Updated Graph")
    plot1.legend(loc='upper left')
    plot2.legend(loc='upper right')
    plot1.grid(True)
    plt.tight_layout()

    canvas.draw()

root = tk.Tk()
root.title("Dynamic Plot")

entry = tk.Entry(root)
entry.pack()

fig = Figure(figsize=(8, 6), dpi=92)
canvas = FigureCanvasTkAgg(fig, master=root)
canvas.get_tk_widget().pack()

plot1 = fig.add_subplot(111)
plot2 = plot1.twinx()

update_button = tk.Button(root, text="Update Plot", command=update_plot)
update_button.pack()

root.mainloop()

只有在使用多个逗号分隔的值(如1,00,1200, 0, 14等)时,上述方法才有效

相关问题