ipywidgets StaticInteract plots all images combination - python

I am using iPython notebook to test interactive functionalities. The following example (from here) worked fine for me several months ago. However, if I run it now, it plots all the images from possible combinations. I am not sure if this is a duplicate, but this didn't help.
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
# mpl.rcParams['figure.max_open_warning'] = 1
def plot(amplitude, color):
fig, ax = plt.subplots(figsize=(4, 3),
subplot_kw={'axisbg':'#EEEEEE',
'axisbelow':True})
ax.grid(color='w', linewidth=2, linestyle='solid')
x = np.linspace(0, 10, 1000)
ax.plot(x, amplitude * np.sin(x), color=color,
lw=5, alpha=0.4)
ax.set_xlim(0, 10)
ax.set_ylim(-1.1, 1.1)
return fig
from ipywidgets import StaticInteract, RangeWidget, RadioWidget
StaticInteract(plot,
amplitude=RangeWidget(0.1, 1.0, 0.1),
color=RadioWidget(['blue', 'green', 'red']))
This is the output:
Can you help me?

This is how you can approach it.
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
from ipywidgets import interact, FloatSlider, RadioButtons
amplitude_slider = FloatSlider(min=0.1, max=1.0, step=0.1, value=0.2)
color_buttons = RadioButtons(options=['blue', 'green', 'red'])
# decorate the plot function with an environment from the UIs:
#interact(amplitude=amplitude_slider, color=color_buttons)
def plot(amplitude, color):
fig, ax = plt.subplots(figsize=(4, 3),
subplot_kw={'axisbg':'#EEEEEE',
'axisbelow':True})
ax.grid(color='w', linewidth=2, linestyle='solid')
x = np.linspace(0, 10, 1000)
ax.plot(x, amplitude * np.sin(x), color=color,
lw=5, alpha=0.4)
ax.set_xlim(0, 10)
ax.set_ylim(-1.1, 1.1)

Related

How do I get rid of the static graph from matplotlib.animation?

Here's the code that produces an animation using matplotlib. When I run it in Jupyter notebook, I also get another static graph below the animated graph. How do I remove it?
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from IPython.display import HTML
fig, ax = plt.subplots()
x = np.arange(0, 20, 0.1)
ax.scatter(x, x + np.random.normal(0, 3.0, len(x)))
line, = ax.plot(x, x - 5, 'r-', linewidth=2)
def update(i):
label = 'timestep {0}'.format(i)
line.set_ydata(x - 5 + i)
ax.set_xlabel(label)
return line, ax
anim = FuncAnimation(fig, update, frames=np.arange(0, 10), interval=200)
HTML(anim.to_html5_video())
I use a module called JSAnimation (see this example notebook from the Author).
To display the animation, you simply call:
from JSAnimation.IPython_display import display_animation
display_animation(anim)

Plot very small values with matplotlib in jupyter

I am trying to plot some extremely small values with matplotlib in jupyter notebook (on a macbook pro). However, regardless if I set the y-axis limits, all I get is a flat line. What I am after is something like the example (png) below with regard to y-axis notation. I also tried the same example outside of jupyter and I still get the same results. Here's the code suggested by Andrew Walker on my previous question:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure(figsize=(13,6))
ax = fig.add_subplot(111)
plt.hold(True)
xs = np.linspace(0, 1, 101)
ys = 1e-300 * np.exp(-(xs-0.5)**2/0.01)
ax.plot(xs, ys, marker='.')
Here's what I get:
And here's what I'm after:
The easiest thing to do is to just plot your values multiplied by 10^300, and then change the y-axis label:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure(figsize=(13,6))
ax = fig.add_subplot(111)
plt.hold(True)
xs = np.linspace(0, 1, 101)
ys = np.exp(-(xs-0.5)**2/0.01)
ax.plot(xs, ys, marker='.')
ax.set_ylabel(r'Value [x 10^{-300}]')
You can use the set_ylim method on your axes object to do what you need, simply change your code to this and it would do what you need:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure(figsize=(13,6))
ax = fig.add_subplot(111)
plt.hold(True)
xs = np.linspace(0, 1, 101)
ys = 1e-300 * np.exp(-(xs-0.5)**2/0.01)
ax.set_ylim([0,10^-299])
ax.plot(xs, ys, marker='.')
you may like to check This link for more info on this subject.

Python subplots not working properly

I am trying to plot three different graphs in three sub-plots within a single figure. Also I want the first figure to be of double width than the other two. Accordingly I have used
gs = gridspec.GridSpec(2, 2, width_ratios=[2,1], height_ratios=[1,1])
But the output has all the figures plotted on ax3.
My code is given here
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
import matplotlib.gridspec as gridspec
gs = gridspec.GridSpec(2, 2, width_ratios=[2,1], height_ratios=[1,1])
ax1=plt.subplot(gs[:,:-1])
ax2=plt.subplot(gs[:-1,-1])
ax3=plt.subplot(gs[-1,-1])
# ax 1
X=np.linspace(0,10,100)
Y=np.sin(X)
ax1 = plt.gca()
ax1.scatter(X, Y)
ax1.axis("tight")
ax1.set_title('ax1')
ax1.set_xlim([0,10])
ax1.set_ylim([-1,1])
plt.xticks([])
plt.yticks([])
# ax 2
ax2 = plt.gca()
vel=np.random.rand(1000)
n, bins, patches = plt.hist(vel, 10, normed=True, histtype='stepfilled', facecolor='green', alpha=1.0)
ax2.set_title('Velocity Distribution')
ax2.axis("tight")
plt.xticks([0,0.05,0.10])
plt.yticks([0,10,20])
# ax 3
Z=np.exp(X)
ax3.plot(X,Z,'red',lw=5)
plt.show()
Can somebody tell me how I can rectify this. Thank you in advance.
Fixed several lines. Please compare with your code.
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
import matplotlib.gridspec as gridspec
gs = gridspec.GridSpec(2, 2, width_ratios=[2,1], height_ratios=[1,1])
ax1=plt.subplot(gs[:,:-1])
ax2=plt.subplot(gs[:-1,-1])
ax3=plt.subplot(gs[-1,-1])
# ax 1
X=np.linspace(0,10,100)
Y=np.sin(X)
#ax1 = plt.gca()
ax1.scatter(X, Y)
ax1.axis("tight")
ax1.set_title('ax1')
ax1.set_xlim([0,10])
ax1.set_ylim([-1,1])
# You can use ax1.set_xticks() and ax1.set_xticklabels() instead.
ax1.set_xticks([])
ax1.set_yticks([])
#plt.xticks([])
#plt.yticks([])
# ax 2
#ax2 = plt.gca()
vel=np.random.rand(1000)
n, bins, patches = ax2.hist(vel, 10, normed=True, histtype='stepfilled', facecolor='green', alpha=1.0)
ax2.set_title('Velocity Distribution')
ax2.axis("tight")
# You can use ax2.set_xticks() and ax2.set_xticklabels() instead.
ax2.set_xticks([0,0.5,1])
ax2.set_yticks([0,1,2])
#plt.xticks([0,0.05,0.10])
#plt.yticks([0,10,20])
# ax 3
Z=np.exp(X)
ax3.plot(X, Z,'red', lw=5)
# You can use ax3.set_xticks() and ax3.set_xticklabels() instead.
ax3.set_xticks([0, 5, 10])
ax3.set_yticks([0, 10000, 20000])
ax3.set_yticklabels(['0', '10K', '20K'])
plt.show()

How to set fontsize of axis label with LaTex symbol on matplotlib/seaborn?

In matplotlib, how can I change the font size of a latex symbol?
I have the following code:
import matplotlib.pyplot as plt
import seaborn as sns
# get x and y from file
plt.plot(x, y, linestyle='--', marker='o', color='b')
plt.xlabel(r'$\alpha$ (distance weighted)', fontsize='large')
plt.ylabel('AUC')
plt.show()
But I get the following graph:
Notice that the $\alpha$ is still small.
To increase the size of the fonts set the desired value to fontsize. One way to mitigate the difference between the "normal" font and the "latex" one is by using \mathrm. The example below shows the behaviour of doing this:
import matplotlib.pyplot as plt
import seaborn as sns
x = np.arange(10)
y = np.random.rand(10)
fig = plt.figure(1, figsize=(10,10))
for i, j in zip(np.arange(4), [10,15,20,30]):
ax = fig.add_subplot(2,2,i+1)
ax.plot(x, y, linestyle='--', marker='o', color='b')
ax.set_xlabel(r'$\mathrm{\alpha \ (distance \ weighted)}$', fontsize=j)
ax.set_ylabel('AUC')
plt.show()

Add minor gridlines to matplotlib plot using seaborn

I'm a fan of the Seaborn package for making nice-looking plots using Matplotlib. But I can't seem to figure out how to show minor gridlines in my plots.
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sbn
x = np.linspace(0, 2 * np.pi, 100)
y = np.sin(x)
fig, ax = plt.subplots(1, 1)
ax.scatter(x, y)
ax.grid(b=True, which='major')
ax.grid(b=True, which='minor')
gives:
Any thoughts here? Also any thoughts on how to adjust the style of the Seaborn gridlines that do show up...in particular, I'd love to make them narrower.
Wound up combining CT Zhu's answer with tcaswell's hint:
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sbn
x = np.linspace(0, 2 * np.pi, 100)
y = np.sin(x)
fig, ax = plt.subplots(1, 1)
ax.scatter(x, y)
ax.get_xaxis().set_minor_locator(mpl.ticker.AutoMinorLocator())
ax.get_yaxis().set_minor_locator(mpl.ticker.AutoMinorLocator())
ax.grid(b=True, which='major', color='w', linewidth=1.0)
ax.grid(b=True, which='minor', color='w', linewidth=0.5)
That's because the minor ticks are not yet defined, so we need to add for example:
ax.set_xticks(np.arange(0,8)-0.5, minor=True)
ax.set_yticks([-1.25, -0.75, -0.25,0.24,0.75,1.25], minor=True)

Categories