plot not showing properly using matplotlib in jupyter notebook - python

I am following a tutorial to plot in real time using python, for some reason my plot is not showing fully. I have no idea why because it is only 3 lines of code and they are exactly the same as the tutorial!
I want to run the code below but as expected I can see it moving but I can't see the entire graph. What is happening here?!
x = []
y = []
i = 0
plt.show()
while True:
x.append(i)
y.append(C3[i])
ax.plot(x, y, color='b')
fig.canvas.draw()
ax.set_xlim(left=max(0, i-50), right=i+50)
time.sleep(0.1)
i += 1
[edit]
Whenever I run
fig = plt.figure()
ax = fig.add_subplot(111)
fig.show()
I get
[IPKernelApp] WARNING | No such comm: bba1ac5ea0484ec7a6446924a4ff37a0
In my terminal

Related

Displaying scatterplot points by points in jupyter notebook

I am trying to display a scatterplot points by points from two arrays :
x = [0,1,2,3,4,5,6,7,8,9,10]
y = [0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5]
I would like to display the point (0,0.5) and add successively the other points ((0.5,1) through (0.5,10)) to the existing plot.
It could be considered as an animated scatterplot indenting points by points.
So far, I have tried the following solutions :
xi=[]
yi=[]
for i in range(10):
xi.append(x[i])
yi.append(y[i])
plt.axhline(y=0.5,color="black",linestyle = '-')
plt.scatter(xi,yi,marker = '+', color="red")
plt.legend()
plt.pause(0.01)
plt.show()
which works perfectly fine in my script (spyder IDE) but not in my jupyter notebook.
Or with the animation function from matplotlib :
frames=20
fig = plt.figure()
ax = plt.gca()
x = [0,1,2,3,4,5,6,7,8,9,10]
y = [0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5]
def scatter_ani(i):
plt.scatter(x[i], y[i],marker = '+', color="red",label="chocs")
anim = animation.FuncAnimation(fig, scatter_ani, frames = frames, interval=50)
anim.save(r"mypath/myanim.gif",writer = animation.PillowWriter(fps=30))
and then,
![mygif](myanim.gif)
in a markdown cell.
How can I display this simple animation in my notebook?
Thank you for your time, I look forward to your insights !

Matplotlib and Celluloid show strange behavior on Jupyter notebook

I am trying to animate the results of a simulation performed with Python. To do so, I'm using matplotlib to generate the frames of the animation and then I collect them with the Camera class from celluloid library. The code that generates the animation is the following:
fig = plt.figure()
ax = plt.gca()
ax.set_aspect('equal')
camera = Camera(fig)
for i in range(result.t.size):
if i % 10 == 0:
x = result.y[0, i]
y = result.y[1, i]
plt.scatter(x, y, s = 100, c = 'red')
plt.xlim(-3, 3)
plt.ylim(-3, 3)
plt.grid()
camera.snap()
animation = camera.animate(blit = False, interval = 10)
HTML(animation.to_html5_video())
The last part that generates an HTML5 video allows for watching the animation in a Jupyter notebook on the web. However, I get the following output:
The first output is the corresponding animation, which is working good. The second is just a static empty plot. So I have two questions:
Where does the second plot come from and how can I remove it?
The animation is not showing any grid, though I requested it via plt.grid() on each frame. Why is that happening?
Thanks in advance for any help.

how to show multiple graphs at once? (class)

Hi everyone:) I would like to ask for some help to make a class that I can use to plot graphs. i have an excel sheet with different countries and their corresponding air pollution levels. i need to plot graphs for each country. this is the code used to plot my graphs:
import matplotlib.pyplot as plt
import numpy as np
x = df_full_filtered.loc[(df_full_filtered['AirPollutant'] == 'PM10') & (df_full_filtered['Country']
== 'Italy')]['AirPollutionLevel']
plt.style.use('ggplot')
plt.hist(x, bins=80)
plt.show()
y = df_full_filtered.loc[(df_full_filtered['AirPollutant'] == 'PM10') & (df_full_filtered['Country']
== 'Germany')]['AirPollutionLevel']
plt.style.use('ggplot')
plt.hist(y, bins=80)
plt.show()
everytime i run my code, it stops running everytime it reaches the plt.show code and wont continue running till you manually close the popup window with the first graph. is there any way i can surpass this?
edit: i tried putting both codes for x and y under each other and inserting plt.plot(x,y) but they have different shapes (rows/columns in the excel file)
thanks
You need to create two figures.
Method 1
data = [i**2 for i in range(100)]
plt.figure(1)
plt.hist(data, bins = 5)
plt.figure(2)
plt.hist(data, bins = 10)
plt.show()
Method 2
data = [i**2 for i in range(100)]
fig1, ax1 = plt.subplots()
ax1.hist(data, bins = 5)
fig2, ax2 = plt.subplots()
ax2.hist(data, bins = 10)
plt.show()
(If you need, you can call them the same name, i.e. the second figure and axes could be named fig1 and ax1, as well.)
Method 1 is the direct answer to your code. Method 2 is another way of using Matplotlib. (see https://matplotlib.org/matplotblog/posts/pyplot-vs-object-oriented-interface/)

Python Several problems of produce GIF by using animation.FuncAnimation

I encountered several problems when I was trying to produce a GIF by using animation function in Python.
Here is my code:
import matplotlib.pyplot as plt
import random
import matplotlib.animation as animation
xdata = []
ydata = []
fig, ax = plt.subplots()
line, = ax.plot(xdata, ydata, marker='o', markeredgewidth=9)
n = -1
def data_gen():
global n
while True:
xdata.clear()
ydata.clear()
for i in range(3):
xdata.append(random.randint(0, 10))
ydata.append(random.randint(0, 10))
n += 1
print('The', n, 'generation')
yield xdata, ydata
def init():
plt.grid()
line.set_linestyle('None')
ax.set_xlim(0, 20)
ax.set_ylim(0, 20)
return line,
def animate(data):
line.set_data(data)
print('data', data)
return line,
ani = animation.FuncAnimation(fig=fig, func=animate, frames=data_gen, init_func=init, interval=200, blit=False)
ani.save('clear list.gif', writer='imagemagick')
plt.show()
Problem 1: There has been a pause (about 10 seconds) since the code started running, in the stage of 0–pause, the GIF can be saved, however, there is a black flash on saved GIF.
Problem 2: At the stage start–pause, I can not see the plot on the screen, after this pause, the plot appeared, the program goes into the normal stage.
Problem 3: I put the code plt.grid() in the function init. When the code is running, I cannot see grid on the plot, however, grid can be seen on the saved plot, why? If I add another code plt.grid() before the last code plt.show(), at this time, the grid will be shown on the plot.
Can someone tell me why this happens?
The code runs in:
IDE: Pycharm 2019.3.4 Professional Edition
Interpreter: Python 3.7
OS: Windows 10
Figure captured when the black shadow appears:

MatPlotLib's ion() and draw() not working

I am trying to plot figures in real time using a for loop. I have the following simple code:
import matplotlib.pyplot as plt
plt.ion()
plt.figure()
for i in range(100):
plt.plot([i], [i], 'o')
plt.draw()
plt.pause(0.0001)
This code does not show the figure until it has finished computing, which I don't want. I want it to draw the figure after every loop. If I replace plt.draw() with plt.show, multiple figures are output in real time, but I want them all to appear in the same figure. Any ideas?
EDIT:
I downloaded PyCharm with Anaconda and everything works fine. I guess it's a problem with Spyder since I tried a few different versions of it without success. If anyone has any clue what is causing this problem in Spyder, let me know!
Adapted for your case from : Python realtime plotting
import matplotlib.pyplot as plt
import numpy as np
import time
fig = plt.figure()
ax = fig.add_subplot(111)
# some X and Y data
x = [0]
y = [0]
li, = ax.plot(x, y,'o')
# draw and show it
fig.canvas.draw()
plt.show(block=False)
# loop to update the data
for i in range(100):
try:
x.append(i)
y.append(i)
# set the new data
li.set_xdata(x)
li.set_ydata(y)
ax.relim()
ax.autoscale_view(True,True,True)
fig.canvas.draw()
time.sleep(0.01)
except KeyboardInterrupt:
plt.close('all')
break
This solution example has worked for me on multiple machines. Try adjusting plt.pause(...)
import matplotlib.pyplot as plt
import numpy as np
F = lambda x: np.sin(2*x)
plt.ion()
x = np.linspace(0, 1, 200)
plt.plot(x, F(x))
for i in range(100):
if 'ax' in globals(): ax.remove()
newx = np.random.choice(x, size = 10)
ax = plt.scatter(newx, F(newx))
plt.pause(0.05)
plt.ioff()
plt.show()
Hey I was having the same problem, I checked other questions and my issue was solved when I plugged a pause into my solution. Here's some example code that worked for me.
import matplotlib.pyplot as plt
import numpy as np
plt.ion()
x = np.arange(0, 4*np.pi, 0.1)
y = [np.sin(i) for i in x]
plt.plot(x, y, 'g-', linewidth=1.5, markersize=4)
plt.pause(0.0001)
plt.plot(x, [i**2 for i in y], 'g-', linewidth=1.5, markersize=4)
plt.pause(0.0001)
plt.plot(x, [i**2*i+0.25 for i in y], 'r-', linewidth=1.5, markersize=4)
plt.pause(0.0001)
The solution was posted here:
Matplotlib ion() and subprocesses
The problem - and the solution - is highly dependent on the plot.draw() function within the Python environment and back end, and may even vary in different product releases. It manifests itself in different ways depending on the environment. The problem shows up in many places on stackoverflow with some solutions working for some people and not for others.
The gold standard on my Windows laptop is running the Python from the command line - no IDE, just plain vanilla Python3. draw() as shown in the example always works fine there.
If I try it in Jupyter notebook on the same machine, no amount of draw(), plot.pause(), plot.show(), or any other suggestion works. I tried %matplotlib with notebook, widget and ipympl. Nothing gets drawn until complete end of cell code execution.
Some other sources on stackoverflow suggested using figure.canvas.flush_events(). I had some success with that and investigated further.
The best solution turned out to be to run the draw() at the figure.canvas level instead of the axes or plot level.
You can get the figure by creating your plot with command:
fig, graph, = plt.subplots()
or, if you've already created the plot, as in the code at the top of the ticket, put the following outside the loop:
fig = plt.gcf() #get current figure
Inside the loop, instead of plt.draw(), use
fig.canvas.draw()
It's proven reliable in my Jupyter Notebook environment even when running multiple axes/plots across multiple figures. I can drop in sleep() statements and everything appears when expected.
Your mileage may vary.

Categories