如何将Legend Matplotlib TKinter

问题描述 投票:0回答:1

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

在我的代码下面:

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

# Create the Tkinter window
root = 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 yLabel
avail.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 = 1
w = 0.2


avail.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 TKinter
canvas_avail = FigureCanvasTkAgg(fig2, master=root)
canvas_avail.get_tk_widget().place(x= 280, y= 150)

root.mainloop()
python matplotlib tkinter
1个回答
0
投票

因此,您将图形放置在 tkinter 窗口几何形状之外的位置,我只是增加了宽度和高度并更改了图形的位置。

我做了一些更改,现在尝试一下:

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

# Create the Tkinter window
root = tk.Tk()
root.geometry('600x450')

fig2, avail = plt.subplots(figsize=(10,7), dpi=60, facecolor= '#e9eef0',)
avail.tick_params(axis='y', labelsize=0)#Formatar a fonte yLabel
avail.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 = 1
w = 0.2


avail.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 TKinter
canvas_avail = FigureCanvasTkAgg(fig2, root)
canvas_avail.get_tk_widget().place(x= 10, y= 0)

root.mainloop()
© www.soinside.com 2019 - 2024. All rights reserved.