Java.beginner
Java.beginner

Reputation: 891

How to set a plot title after plot window is closed in Python

I want to change the plot title based on the user selection after the plot window is closed.

    ax = pd.rolling_mean(dataToPlot_plot[startTime:endTime][['plotValue']],mar).plot(linestyle='-', linewidth=3,  markersize=9, color='#FECB00')
    ax.legend().set_visible(False)
    titObj = plt.title('Data Plot - '+"\n", fontsize=13)#plot title
    plt.show()#showing the plot

    fig = ax.get_figure()
    fig.set_size_inches(12, 6)
    fig.savefig(savePlot)

Now I need change the plot title dynamically based on the user selection on the plot and save it...

    ax = pd.rolling_mean(dataToPlot_plot[startTime:endTime][['plotValue']],mar).plot(linestyle='-', linewidth=3,  markersize=9, color='#FECB00')
    ax.legend().set_visible(False)
    titObj = plt.title('Data Plot - '+"\n", fontsize=13)#plot title
    plt.show()#showing the plot

    curVal = ax.get_xlim()
    stdate = int(curVal[0])
    endate = int(curVal[1])
    difdate = endate - stdate 

    fig = ax.get_figure()
    if stdate > 0 and endate > 0:
        if difdate > 365:
            newplotTitle = 'Data Plot - Since from start'
        elif difdate > 28 and difdate < 365:
            newplotTitle = 'Data Plot - Past Month'
        elif difdate < 28:
            newplotTitle = 'Data Plot - Past Days'

        plt.title(newplotTitle+"\n", fontsize=13)#plot title

    fig.set_size_inches(12, 6)
    fig.savefig(savePlot)

The new changes is not amending with the old title, Is there any other way to fix this... Thanks in advance...

Upvotes: 1

Views: 335

Answers (1)

Joe Kington
Joe Kington

Reputation: 284602

What's happening is that the plt interface always refers to the "current" figure/axes/etc.

After you've closed the figure, the "current" axes is a new, blank plot.

For this and several other reasons, it's best to stick to the axes methods (except for a handful of functions like plt.figure, plt.subplots, plt.show, etc that make dealing with creating and displaying figures easier).

Using the methods of the axes or figure objects make the relationship to which axes/figure is being modified much more clear. Otherwise, you need to be aware of what the "current" axes is.


In your case, rather than doing plt.title('blah'), use ax.set(title='blah') (or ax.set_title) instead.

Upvotes: 1

Related Questions