Matplotlib graph not being constrained as expected in frame

38 views Asked by At

As the root window resizes, the figure embedded into the frame will grow and shrink unproportionally and allows parts of the figure to be "cut-off" (i.e. the window edge moves past the bounds of the figure). Is there a way for the figure to hold its proportions/boundaries better?

import CTkGraph
import tkinter as tk

if __name__ == '__main__':
    root = tk.Tk()
    root.geometry("800x600")
    root.rowconfigure(0, weight=1, uniform='u')
    root.columnconfigure(0, weight=1, uniform='u')
    graph = CTkGraph.CTkGraph(root)
    graph.grid(row=0, column=0, sticky="nsew")
    root.mainloop()

Graph Class

import tkinter as tk
import customtkinter as ctk

from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg, NavigationToolbar2Tk)
from matplotlib.ticker import StrMethodFormatter
import matplotlib.pyplot as plt

import numpy as np
import pandas as pd

class CTkGraph(ctk.CTkFrame):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        allowed_keys = ['dataframe', 'xlabel', 'colors']
        x = np.arange(0, 3, .01)
        y = 2 * np.sin(2 * np.pi * x)
        self.dataframe = pd.DataFrame({'x': x, 'y': y})
        self.xlabel = 'x'
        self.ylabel = 'y'
        self.default_color = 'black'
        self.colors = {}

        for key, value in kwargs.items():
            if key in allowed_keys:
                setattr(self, key, value)

        for column in self.dataframe.columns:
            if column != self.xlabel:
                self.colors.setdefault(column, self.default_color)

        self.fig, self.ax = plt.subplots(layout='tight')

        self.canvas = FigureCanvasTkAgg(self.fig, master=self)
        self.plot()



    def plot(self):
        self.ax.cla()
        self.ax.yaxis.set_major_formatter(StrMethodFormatter('{x:,.1f}'))
        self.ax.set_xlabel(self.xlabel)
        self.ax.set_ylabel(self.ylabel)

        for column in self.dataframe.columns:
            if column != self.xlabel:
                self.ax.plot(self.dataframe[self.xlabel], self.dataframe[column], self.colors[column], linewidth=1)

        self.fig.tight_layout()
        self.canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True)
        self.canvas.draw()

Normal View: normal view

Unwanted Behavior (x axis label is being cut off): unwanted behavior

0

There are 0 answers