Home > Back-end >  matplotlib: Second empty window on plt.show()
matplotlib: Second empty window on plt.show()

Time:09-02

I usually don't ask questions on this platform, but I have a problem that quite bugs me.

Context

I have a function that plots data from a dataframe that has stockdata. It all works perfectly except for the fact that a second, empty window shows next to the actual graph whenever I execute this function. (image)

Here is all the relevant code, I'd be very grateful if some smart people could help me.

    def plot(self):
    plt.clf()
    plt.cla()
    colors = Colors()
    data = self.getStockData()
    if data.empty:
        return
    data.index = [TimeData.fromTimestamp(x) for x in data.index]
    current, previous = data.iloc[-1, 1], data.iloc[0, 1]
    percentage = (current / previous - 1) * 100
    # Create a table
    color = colors.decideColorPct(percentage)
    # Create the table
    fig = plt.figure(edgecolor=colors.NEUTRAL_COLOR)
    fig.patch.set_facecolor(colors.BACKGROUND_COLOR)
    plt.plot(data.close, color=color)
    plt.title(self.__str2__(), color=colors.NEUTRAL_COLOR)
    plt.ylabel("Share price in $", color=colors.NEUTRAL_COLOR)
    plt.xlabel("Date", color=colors.NEUTRAL_COLOR)
    ax = plt.gca()

    ax.xaxis.set_major_formatter(plt_dates.DateFormatter('%Y/%m/%d %H:%M'))
    ax.set_xticks([data.index[0], data.index[-1]])
    ax.set_facecolor(colors.BACKGROUND_COLOR)
    ax.tick_params(color=colors.NEUTRAL_COLOR, labelcolor=colors.NEUTRAL_COLOR)
    for spine in ax.spines.values():
        spine.set_edgecolor(colors.NEUTRAL_COLOR)

    ax.yaxis.grid(True, color=colors.NEUTRAL_COLOR, linestyle=(0, (5, 10)), linewidth=.5)
    plt.show()

Some notes:

Matplotlib never gets used in the program before this.

The data is standardized and consists of the following columns: open, low, high, close, volume.

The index of the dataframe exists of timestamps, which gets converted to an index of datetime objects at the following line: data.index = [TimeData.fromTimestamp(x) for x in data.index]

CodePudding user response:

Remove plt.clf() and plt.cla() because it automatically creates window for plot when you don't have this window.

And later fig = plt.figure() creates new window which it uses to display your plot.


Minimal code for test

import matplotlib.pyplot as plt
import pandas as pd

data = pd.DataFrame({'x': [1,2,3], 'y': [2,3,1]})

#plt.clf()
#plt.cla()
fig = plt.figure()
plt.plot(data)
ax = plt.gca()
plt.show()
  • Related