'plt.ion() matplotlib makes pycharm crash, i think

I'm trying to create a piece of code that reads two lists x[] and y[] and plots them.

But I also want to input manually my y values while my x values increments every loop.

to make this possible I use the function plt.ion() but when I'm using it into the program it opens the plot's window that immediately crashes

This is strange because on replit the code works fine (on pycharm doesn't)

I don't know what I'm doing wrong

here is the code:

import time
import matplotlib.pyplot as plt

x = []
T = 0
y = []

fig, ax = plt.subplots() # Create a figure containing a single axes.plt.ion()

while True:
 x.append(T)
 y.append(int(input()))
 ax.plot(x, y)    #plots the values
 plt.show()    #shows the plot
 print(x, y)   #only to know if the program is running, spoiler no
 T+= 1
 time.sleep(1)


Solution 1:[1]

I tried it on a regular Python interpreter, and there are a few things to fix:

  • you need to run plt.ion(), which were commented out in your code.
  • for each input, you were adding a line with a single point, which will not be rendered. Instead, you need to create a line first, then update its values.
  • we also need to provide initial axis limits. Eventually, this can be updated inside the while loop.
import matplotlib.pyplot as plt
import numpy as np

x = []
T = 0
y = []

fig, ax = plt.subplots()
plt.ion()
line, = ax.plot(x, y)

# Need to set axis limits
ax.set_xlim(0, 10)
ax.set_ylim(0, 10)
plt.show()

while True:
    x.append(T)
    y.append(int(input()))
    # NOTE: `line.set_data` expects numpy arrays as parameters, not list!
    line.set_data(np.array(x), np.array(y))    # update the values
    T += 1
    time.sleep(1)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Davide_sd