我想让我的绘图适合图形的大小,其中包括 x 轴和 y 轴的标签。问题是标签被缩放推到了图形之外。
因为我同时处理多个帧,所以绘图具有预定义的大小很重要。我试图使代码尽可能短,只保留代码的本质。
在代码中,tkinter 中有多个实时绘图,都有自己的框架,但属于同一类。
import matplotlib
import matplotlib.animation as animation
matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg,
NavigationToolbar2TkAgg
from matplotlib.figure import Figure
import matplotlib.animation as animation
import matplotlib as plt
import tkinter as tk
from tkinter import ttk
from math import *
figure_1 = Figure(figsize=(4,2.5), dpi=100)
a1 = figure_1.add_subplot(111)
figure_2 = Figure(figsize=(4,2.5), dpi=100)
a2 = figure_2.add_subplot(111)
x_value_1 =[]
y_value_1 =[]
x_value_2 =[]
y_value_2 =[]
var =tk.Tk()
def plot_1_xy(i):
x_value_1.append(i)
z=sin(pi*x_value_1[i]/9)
y_value_1.append(z)
a1.clear()
a1.plot(x_value_1,y_value_1)
a1.set_xlabel('X Label')
a1.set_ylabel('Y Label')
def plot_2_xy(i):
x_value_2.append(i)
y_value_2. append(500*sin((1/14)*pi*i))
a2.clear()
a2.plot(x_value_2,y_value_2)
a2.set_xlabel('X Label')
a2.set_ylabel('Y Label')
class Question_online():
def __init__(self,master):
self.frame = tk.Frame(master)
plot_frame(self.frame,0)
plot_frame(self.frame,1)
self.frame.pack()
class plot_frame(tk.Frame):
def __init__(self,root,j=0):
self.j = j
self.figure_name = [figure_1,figure_2]
self.frame = tk.Frame(root)
self.canvas = FigureCanvasTkAgg(self.figure_name[j], self.frame)
self.canvas.show()
self.canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH,
expand=True)
self.canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=1)
self.frame.pack()
c = Question_online(var)
ani = animation.FuncAnimation(figure_1,plot_1_xy,interval=500)
ani1 = animation.FuncAnimation(figure_2,plot_2_xy,interval=500)
var.mainloop()
最佳答案
您可以在每次图形更新时调用 Figure 的 tight_layout()
方法以确保显示您的标签:
def plot_1_xy(i):
x_value_1.append(i)
z=sin(pi*x_value_1[i]/9)
y_value_1.append(z)
a1.clear()
a1.plot(x_value_1,y_value_1)
a1.set_xlabel('X Label')
a1.set_ylabel('Y Label')
figure_1.tight_layout()
def plot_2_xy(i):
x_value_2.append(i)
y_value_2. append(500*sin((1/14)*pi*i))
a2.clear()
a2.plot(x_value_2,y_value_2)
a2.set_xlabel('X Label')
a2.set_ylabel('Y Label')
figure_2.tight_layout()
关于python - 绘图标签位于 tkinter Canvas 上的图形之外,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50524188/