Why cant i use sliders in google colab? - python

Im trying to make a plot with a slider to adjust the variables to visualize changes in lines.
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider, Button
x = list(range(0,11))
y = [10] * 11
fig, ax = plt.subplots()
plt.subplots_adjust(left=0.1, bottom=0.35)
p, =plt.plot(x,y, linewidth=2, color='blue')
plt.axis([0,10, 0, 100])
axSlider1 = plt.axes([0.1,0.2, 0.8, 0.05])
slder1 = Slider(axSlider1, 'Slider 1', valmin=0, valmax=100)
axSlider2 =plt.axes([0.1,0.1, 0.8, 0.05])
slder2 = Slider( ax=axSlider2,
label='Slider2',
valmin=0,
valmax=100,
valinit=30,
valfmt='%1.2f',
closedmax=False)
i used this code and itll plot perfectly but i cant slide the slider in colab.

Related

plot an input point on a image with pyplot

I want to plot an image with pyplot and on top of that image a point.
That point is from an input field in the pyplot. Here I have a piece of code, where you can put a point in, but after pressing enter, or search button it won't plot the point. Here is my code:
import cv2
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import TextBox
def imshow_rgb(img_bgr):
img_rgb = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB)
plt.imshow(img_rgb)
ims = cv2.imread('plattegrondtekening.png', 1)
fig = plt.imshow(np.flipud(ims), cmap='gray', origin='lower')
plt.subplots_adjust(bottom=0.2)
initial_text = ""
x,y=[500,500]
def submit(text):
x,y = list(map(int,text.split(",")))
print(x,y)
plt.plot(x, y, "ro")
plt.show()
axbox = plt.axes([0.1, 0.05, 0.8, 0.075])
text_box = TextBox(axbox, 'search', initial=initial_text)
text_box.on_submit(submit)
plt.show()
image plot with input field below, this is the output of the code above
But I want that it shows a point on x=900 and y=800, when I enter 900,800 in the input box.
We have to select the active axes first using plt.sca(ax) and for refreshing the canvas we may use fig.canvas.draw() and fig.canvas.flush_events().
Replace fig = plt.imshow(np.flipud(ims), cmap='gray', origin='lower') with:
fig = plt.figure() # Keep the figure for later usage.
ax = plt.gca() # Keep the axes for later usage.
ax.imshow(np.flipud(ims), cmap='gray', origin='lower') # Show the image on axes ax
Replace plt.plot(x, y, "ro") and plt.show() with:
plt.sca(ax) # Set active axes
plt.plot(x, y, "ro")
fig.canvas.draw() # Refresh the canvas.
fig.canvas.flush_events()
Code sample:
import cv2
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import TextBox
ims = cv2.imread('plattegrondtekening.png', 1)
fig = plt.figure() # Keep fig for later usage
ax = plt.gca() # https://stackoverflow.com/questions/25505341/how-to-get-the-axesimages-from-matplotlib
ax.imshow(np.flipud(ims), cmap='gray', origin='lower')
plt.subplots_adjust(bottom=0.2)
initial_text = ""
x,y=[500,500]
def submit(text):
x, y = list(map(int,text.split(",")))
print(x,y)
plt.sca(ax) # https://stackoverflow.com/questions/19625563/matplotlib-change-the-current-axis-instance-i-e-gca
plt.plot(x, y, "ro")
fig.canvas.draw() # https://stackoverflow.com/questions/4098131/how-to-update-a-plot-in-matplotlib
fig.canvas.flush_events()
axbox = plt.axes([0.1, 0.05, 0.8, 0.075])
text_box = TextBox(axbox, 'search', initial=initial_text)
text_box.on_submit(submit)
plt.show()

Matplotlib more efficient way to update chart when using slider to scroll through chart?

I want to be able to scroll through a lengthy chart. Is there a more efficient/faster way than having to clear the axis and replot the whole thing every time the scroll bar moves?
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider
import random
x=[c for c in range(300)]
y=[random.randint(1,10) for c in range(300)]
showbars=100
fig = plt.figure()
ax = plt.subplot(111)
ax.bar(x[:showbars],y[:showbars])
def slidebar(pos):
pos = int(pos)
ax.clear()
ax.bar(x[pos:pos+showbars],y[pos:pos+showbars])
slidebarpos = plt.axes([0.1, 0.01, 0.5, 0.03], facecolor="skyblue")
slider = Slider(slidebarpos, '', 0, len(x)-showbars, valinit=0)
slider.on_changed(slidebar)
slidebar(0)
plt.show()
This is slow on my computer
First of all you could plot the bars only once, and use the slider just to change the range that is shown, i.e. the limits of the x-axis.
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider
import numpy as np
x=np.arange(300)
y=np.random.randint(1,10, size=300)
showbars=100
fig, ax = plt.subplots()
ax.bar(x,y)
def slidebar(pos):
ax.set_xlim(pos-1, pos+showbars+1)
slidebarpos = plt.axes([0.1, 0.01, 0.5, 0.03], facecolor="skyblue")
slider = Slider(slidebarpos, '', 0, len(x)-showbars, valinit=0)
slider.on_changed(slidebar)
slidebar(0)
plt.show()
One could also keep the same bar's in place, but change their height and fake the ticks and labels in such a way that the bars look like being updated.
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider
from matplotlib.ticker import AutoLocator
import numpy as np
x=np.arange(300)
y=np.random.randint(1,10, size=300)
showbars=100
fig, ax = plt.subplots()
bars = ax.bar(x[:showbars],y[:showbars])
loc = AutoLocator()
def slidebar(pos):
pos = int(pos)
for bar, yi in zip(bars, y[pos:showbars+pos]):
bar.set_height(yi)
ticks = loc.tick_values(pos, showbars+pos)
ax.set_xticks(ticks-pos)
ax.set_xticklabels(ticks)
slidebarpos = plt.axes([0.1, 0.01, 0.5, 0.03], facecolor="skyblue")
slider = Slider(slidebarpos, '', 0, len(x)-showbars, valinit=0)
slider.on_changed(slidebar)
slidebar(0)
plt.show()

Jupyter Notebook matplotlib notebook makes plot not show up, inline makes it not interactive

I have one python file Vis.py with the following two functions:
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider
def update(val): #needed for slider function of plot_test
pos = spos.val
ax.axis([pos,pos+10,-1,1])
fig.canvas.draw_idle()
def plot_test(data):
fig, ax = plt.subplots()
plt.subplots_adjust(bottom=0.25)
plt.plot(data)
plt.axis([0, 10, -1, 1])
axcolor = 'lightgoldenrodyellow'
axpos = plt.axes([0.2, 0.1, 0.65, 0.03], facecolor=axcolor)
spos = Slider(axpos, 'Pos', 0.1, 90.0)
spos.on_changed(update)
plt.show();
and I am trying to use the plot_test function in a separate ipynb file:
%matplotlib notebook
from Vis import *
import numpy as np
t = np.arange(0.0, 200.0, 0.1)
s = np.sin(2*np.pi*t)
plot_test(s)
However, the plot doesn't show up, not even an empty white space. I tried running %matplotlib inline before plot_test(s). That makes the plot show up, but it also gets rid of the interactiveness of the plot.
The updating function references ax, which is out of scope. A solution is to put the updating function inside the plot_test function.
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider
def plot_test(data):
fig, ax = plt.subplots()
plt.subplots_adjust(bottom=0.25)
plt.plot(data)
plt.axis([0, 10, -1, 1])
axcolor = 'lightgoldenrodyellow'
axpos = plt.axes([0.2, 0.1, 0.65, 0.03], facecolor=axcolor)
spos = Slider(axpos, 'Pos', 0.1, 90.0)
def update(val): #needed for slider function of plot_test
pos = spos.val
ax.axis([pos,pos+10,-1,1])
fig.canvas.draw_idle()
spos.on_changed(update)
plt.show()
Then, keeping the notebook part unchanged,
%matplotlib notebook
from Vis import *
import numpy as np
t = np.arange(0.0, 200.0, 0.1)
s = np.sin(2*np.pi*t)
plot_test(s)
results in the desired interactive figure for me.

how to plot multiple legends from a list

I am trying to iterate over multiple plots each with their own labels. The legend values are taken from the list 'iou'. The code below only generates 1 label for iou=0.2. Any help is appreciated.
iou=[0.2, 0.4, 0.6, 0.8]
from matplotlib import pyplot as plt
fig = plt.figure()
for i in range(0,4):
p=plt.plot(recall[i], precision[i], marker='+')
plt.legend(p, iou)
plt.title("PR curves")
plt.xlabel("Recall")
plt.ylabel("Precision")
In each iteration of your loop you'll want to use the label attribute of plt.plot and only after the loop call to plt.legend
from matplotlib import pyplot as plt
iou=[0.2, 0.4, 0.6, 0.8]
fig, ax = plt.subplots(1, 1)
for i in range(0,4):
ax.plot(recall[i], precision[i], marker='+', label=iou[i])
fig.legend()
ax.set_title("PR curves")
ax.set_xlabel("Recall")
ax.set_ylabel("Precision")
A minimal working example could be the following:
from matplotlib import pyplot as plt
import numpy as np
iou=[0.2, 0.4, 0.6, 0.8]
precision = np.random.randint(0, 10, size=(4, 10))
fig, ax = plt.subplots(1, 1)
for i in range(0,4):
ax.plot(np.r_[:10], iou[i] * precision[i], marker='+', label=iou[i])
fig.legend()
ax.set_title("PR curves")
ax.set_xlabel("Recall")
ax.set_ylabel("Precision")
Which gives the following:

changes axis of scatter plot with slider matplotlib python

I have a very large data set and want the user to be able to slide along the axis to view sections of the data. I'm trying to leverage off of the slider example but I'm unsure of how to update the graph. Hoping someone can explain some of the behinds the scenes with this.
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.widgets import Slider, Button, RadioButtons
fig = plt.figure()
ax = fig.add_subplot(111)
fig.subplots_adjust(left=0.25, bottom=0.25)
min0 = 0
max0 = 10
x = np.arange(10)
y = np.arange(10)
im1 = plt.scatter(x,y, s=3, c=u'b', edgecolor='None',alpha=.75)
#most examples here return something iterable
plt.ylim([0,10])#initial limits
axcolor = 'lightgoldenrodyellow'
axmin = fig.add_axes([0.25, 0.1, 0.65, 0.03], axisbg=axcolor)
axmax = fig.add_axes([0.25, 0.15, 0.65, 0.03], axisbg=axcolor)
smin = Slider(axmin, 'Min', 0, 10, valinit=min0)
smax = Slider(axmax, 'Max', 0, 10, valinit=max0)
def update(val):
plt.ylim([smin.val,smax.val])
ax.canvas.draw()#unsure on this
smin.on_changed(update)
smax.on_changed(update)
plt.show()
The graph updates itself when you set new limits. You just don't see this because you update wrong subplot. Just select right subplot to update:
def update(val):
plt.subplot(111)
plt.ylim([smin.val,smax.val])
(this work for me)
or maybe even:
def update(val):
plt.ylim([smin.val,smax.val])
plt.subplot(111)
smin.on_changed(update)
smax.on_changed(update)
if you don`t do anything with it elsewhere
UPD: also in matplotlib examples you can find fig.canvas.draw_idle()

Categories

Resources