1

I wrote a very simple code in which I ask the user an input. If the user types "y" I want to plot a linechart. If the user types "n" the loop breaks.
I'm using Spyder IDE and I want the linechart to be plotted on a separate window in order to zoom and navigate the plot with the toolbar.
I encountered this problem, whenever I plot the plot windows freezes and it crashes (like in the image):

enter image description here

This is the code I've written:

import random
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np

def plot_random():
    x1 = np.linspace(0,100,100)
    y1 = np.random.rand(100)
    
    title = 'Title of the plot'
    sns.set_style("whitegrid")
    plt.ion()
    line_plot = sns.lineplot(x=x1, y=y1)
    line_plot.set_title(title)
    line_plot.set(xlabel='xlabel', ylabel='ylabel')
    plt.show()
    plt.pause(5)    
    
while True:
    plotTF = input('Do you want to plot? (Y/N) ').lower()
    
    if plotTF == 'n':
        break
    elif plotTF == 'y':
        plot_random()
    else:
        print('Not a valid entry')

Before adding plt.pause(5) the graph wasn't even plotted, but it popped a white plot window which immediately crashed.
Now it plots and crashes after the 5 second.
I want the plot to stay "zoomable" and "navigable" all the time till the user gives an other input.
How can I solve the problem?

Zephyr
  • 11,891
  • 53
  • 45
  • 80
riccardo
  • 17
  • 4
  • @riccado, why don't you use animation with matplotlib? – I'mahdi Aug 26 '21 at 08:25
  • @user1740577 it may be the solution but I'm new to python and I never used it. I tried but with no working outcome. Can you address me to some useful examples? Thank you! – riccardo Aug 26 '21 at 08:32
  • is this answer helps you? https://stackoverflow.com/questions/43445103/inline-animations-in-jupyter – I'mahdi Aug 26 '21 at 09:36

1 Answers1

0

Just remove plt.ion() and plt.pause(5) in plot_random function.
(Tested in PyCharm)

def plot_random():
    x1 = np.linspace(0, 100, 100)
    y1 = np.random.rand(100)

    title = 'Title of the plot'
    sns.set_style("whitegrid")
    line_plot = sns.lineplot(x = x1, y = y1)
    line_plot.set_title(title)
    line_plot.set(xlabel = 'xlabel', ylabel = 'ylabel')
    plt.show()
Zephyr
  • 11,891
  • 53
  • 45
  • 80
  • Thank you for your answer. I did as you suggested but the problem remains. Now, without the pause, it doesn't even plot the line but it pops only a white crashed window. Instead I noticed that when I end the loop the graph is shown correctly, the problem is I want to be able to navigate the graph while I'm in the loop. – riccardo Aug 26 '21 at 08:21
  • I may be wrong but I suspect it is an issue with Spyder IDE. Your code, with the above suggestion, work fine in PyCharm IDE. Which version of matplotlib are you using? – Zephyr Aug 26 '21 at 08:23
  • Version 3.3.4 of matplotlib – riccardo Aug 26 '21 at 08:29