我想将我的情节与图的大小相匹配,其中包括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()
答案 0 :(得分:1)
您可以在每个数字更新时调用图的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()