Is there a way to reset fig.canvas.manager.set_window_title()? (overlapping window titles)

Viewed 131

I tried to do a wrap function around the plotting class, however when I save my plots first function looks good, however in second fig_name overlaps on each other. I am guessing the problems is fig.canvas.manager.set_window_title(fig_name)(I use this name function because I might use more than one axis plot in one figure). Here is my image that I would like to fix:

enter image description here

My example code:

import numpy as np
import matplotlib.pyplot as plt


# figure creating and saving wrapper
def figure_wrapper(func):
    def wrapper(*args,**kwargs):
        fig, ax, x_label, y_label, axs_name, fig_name = func(*args,**kwargs)
        for ax_name in axs_name:
            ax.set_title(ax_name, fontweight='bold', size='22')
        ax.legend()
        ax.set_xlabel(x_label, fontweight='bold')
        ax.set_ylabel(y_label, fontweight='bold')
        fig.canvas.manager.set_window_title(fig_name)
        fig.savefig(fig_name, bbox_inches='tight', dpi=1200)
        plt.close(fig)
    return wrapper

# plotting class
class plotting():
    def __init__(self):
        self.fig=plt.figure()

    @figure_wrapper
    def plot(self,x,y):
        ax_name = 'plot1'
        axs_name = [ax_name]
        fig_name = "Some nice name for plot figure 1"
        ax = self.fig.add_subplot(label=ax_name)
        x_label = "R \u03A9"
        y_label = "L \u03BCm"
        ax.plot(x,y,label= '1')
        ax.set_title(ax_name, fontweight='bold', size='22')
        return self.fig, ax, x_label, y_label, axs_name, fig_name

    @figure_wrapper
    def scatter(self,x,y,):
        ax_name = 'scatter1'
        axs_name = [ax_name]
        fig_name = "Even better name for plot figure 2"
        ax = self.fig.add_subplot(label=ax_name)
        x_label = "R \u03A9"
        y_label = "L \u03BCm"
        ax.scatter(x, y,label= '2')
        return self.fig, ax, x_label, y_label, axs_name, fig_name

# data for plotting
x = np.linspace(0, 10, 10)
y = np.linspace(20, 30, 10)
x1 = np.linspace(20, 10, 10)
y1 = np.linspace(60, 30, 10)

# execution of class
plotting = plotting()
plotting.plot(x,y)
plotting.scatter(x,y)
1 Answers

You have to create new figure for every plot

    @figure_wrapper
    def plot(self, x, y):

        self.fig = plt.figure()

        # ... code ...

    @figure_wrapper
    def scatter(self, x, y):

        self.fig = plt.figure()

        # ... code ...

Or you have to clear() existing figure.

    @figure_wrapper
    def plot(self, x, y):

        self.fig.clear()

        # ... code ...

    @figure_wrapper
    def scatter(self, x, y):

        self.fig.clear()

        # ... code ...

Problem can be because every plot uses self.fig.add_subplot(label=ax_name) so it adds new plot to existing plot. And it has nothing to do with set_title()

Related