PHP前端开发

如何将图例Matplotlib TKinter

百变鹏仔 1天前 #Python
文章标签 如何将
问题内容

我正在尝试在图形中创建图例,但当我使用 legend() 时它不起作用。我不知道还能有什么。我看到了很多关于它的信息,我也在做同样的事情,但它一直不起作用。你能帮我一下吗?

在我的代码下面:

import tkinter as tkimport matplotlib.pyplot as pltfrom matplotlib.figure import Figurefrom matplotlib.backends.backend_tkagg import FigureCanvasTkAggfrom matplotlib import animationimport random# Create the Tkinter windowroot = tk.Tk()root.geometry('400x100')fig2, avail = plt.subplots(figsize=(10,7), dpi=60, facecolor= '#e9eef0',)avail.tick_params(axis='y', labelsize=0)#Formatar a fonte yLabelavail.set_ylabel('FOLLOWING THE PRODUCTION', fontsize=20)avail.set_xlabel('TIME (minute)', fontsize=20)avail.legend(['ON','PLANNED','STOP'])       stop = [30]on = [40]planned = [70]  x = 1w = 0.2avail.barh(x + w, on ,w, color='#22e3e3', edgecolor = 'black', linewidth = 2)avail.barh(x, planned , w ,color='#05337d', edgecolor = 'black', linewidth = 2)avail.barh(x - w, stop, w, color = '#c95924', edgecolor = 'black', linewidth = 2)#criando figura para plotar dentro do TKintercanvas_avail = FigureCanvasTkAgg(fig2, master=root)canvas_avail.get_tk_widget().place(x= 280, y= 150)root.mainloop()

正确答案


进行一些更改并指出错误后,这是另一个代码,这次它可以工作并显示图例:

import tkinter as tkimport matplotlib.pyplot as pltfrom matplotlib.figure import Figurefrom matplotlib.backends.backend_tkagg import FigureCanvasTkAggroot = tk.Tk()root.geometry('600x450')fig2, avail = plt.subplots(figsize=(10,7), dpi=60, facecolor='#e9eef0',)avail.tick_params(axis='y', labelsize=0)avail.set_ylabel('FOLLOWING THE PRODUCTION', fontsize=20)avail.set_xlabel('TIME (minute)', fontsize=20)stop = [30]on = [40]planned = [70]x = 1w = 0.2avail.barh(x + w, on, w, color='#22e3e3', edgecolor='black', linewidth=2)avail.barh(x, planned, w, color='#05337d', edgecolor='black', linewidth=2)avail.barh(x - w, stop, w, color='#c95924', edgecolor='black', linewidth=2)# Legend added after creating barsavail.legend(['ON', 'PLANNED', 'STOP'])#criando figura para plotar dentro do TKintercanvas_avail = FigureCanvasTkAgg(fig2, master=root)canvas_avail.get_tk_widget().place(x=10, y=0)root.mainloop()

证明: