Python Widget - How made this plot? - python

I know that if I want plot/print something with the widget, i should use the following code:
interact(function,variable=(1,3))
Now I am facing a problem. Is it possible create a widget that have as input two arrays? for example, consider the case when:
a= np.linspace(1,2,100)
b= np.linspace(3,4,100)
Is it possible see the behaviour of a function, with two different arrays (e.g. switch from the interval a, to the interval b)?
Below I have tried something, but it does not works..
import numpy as np
import matplotlib.pyplot as plt
from __future__ import print_function
from ipywidgets import interact, interactive, fixed, interact_manual
import ipywidgets as widgets
a= np.linspace(1,2,100)
b= np.linspace(3,4,100)
def test(array,constant):
f = []
for x in array:
f.append(x**2+constant*x)
plt.plot(f)
plt.show()
return f
interact(test,array=(a,b),constant=(1,5))

You can try something like this:
import numpy as np
import matplotlib.pyplot as plt
from __future__ import print_function
from ipywidgets import interact, interactive, fixed, interact_manual
import ipywidgets as widgets
xs = {"a": np.linspace(1, 2, 100), "b": np.linspace(3, 4, 100)}
def test(constant, array):
x = xs[array]
f = x**2*constant*x
plt.plot(x, f)
plt.show()
interact(test, array=xs.keys(), constant=(1,5))
It will create a widget with a slider to control the constant value and a pull down menu to select one of the two arrays.

Related

Plotting a curve that is fed by a function

import numpy as np
import scipy.stats as stats
import math
import ipywidgets as widgets
from ipywidgets import interactive
import seaborn as sns
import matplotlib.pyplot as plt
mu_0 = 50
mu_1 = mu_0*1.1
#mu_2 = mu_0*1.5
n= 3
sigma=4.32/math.sqrt(n)
horizontal_values=np.linspace(55, 75, num=101)
def critical_value(mu_1,sigma, alpha=0.04):
c=stats.norm.ppf(1-alpha,mu_0,sigma)
return c
c= critical_value(mu_1,sigma)
power = stats.norm.sf(c,mu_1,sigma)
print (power)
print(c)
Hello,
I need to plot a graph from these data: so when you enter different mu_0 you get different powers
I need to enter every element in that array(horizontal values) to that function(the one that calculates the power so we can see the power in accordance to the speed)
And after that I want to draw a curve accordingly.
TLDR I want to change mu_0 between 55 and 75 and use the results to draw a graph. However I dont know how to go about it.
I think this is what you are looking for.
import numpy as np
import scipy.stats as stats
import math
import ipywidgets as widgets
from ipywidgets import interactive
import seaborn as sns
import matplotlib.pyplot as plt
def critical_value(mu_1,sigma, alpha=0.04):
c=stats.norm.ppf(1-alpha,mu_0,sigma)
return c
def func(mu_0): # function for calculating power
mu_1 = mu_0*1.1
#mu_2 = mu_0*1.5
n = 3
sigma=4.32/math.sqrt(n)
c = critical_value(mu_1,sigma)
power = stats.norm.sf(c,mu_1,sigma)
return power
horizontal_values=np.linspace(55, 75, num=101)
power = [func(mu) for mu in horizontal_values] # calculates power for different mu_0
plt.plot(horizontal_values, power) # plot
plt.xlabel('mu')
plt.ylabel('Power')
plt.show()

List of matrices: plot each element of matrix as a function of an index

I have a list of matrices. I would like to plot each element of those matrices in function of another list.
However I am struggling to do it without using a loop.
How can I do it in the simplest way ?
Below a code explaining a little bit more what I want to do.
import numpy as np
from numpy import *
from matplotlib.pyplot import *
import matplotlib.pyplot as plt
from mpmath import *
import mpmath as mpmath
import pylab
import numpy
import time
import math
from qutip.sparse import sp_eigs
import numpy, scipy.io
from random import *
randomMatrixList=[np.random.rand(2,2) for _ in range(10)]
index=np.arange(10)
# I want to plot on x axis: index, on y axis: randomMatrixList[ii][0] for ii
# corresponding to index[ii] for the "0" curve, then randomMatrixList[ii][1] for the first one, and so on
I don't think there is any way to do this completely without loops, but this way is somewhat compact. There is further cleverness to be done if you want, but the code below is a trade off in terms of explicitness and ease to understand.
import numpy as np
import matplotlib.pyplot as plt
randomMatrixList = [np.random.rand(2, 2) for _ in range(10)]
index = np.arange(10)
stacked_matrices = np.array(randomMatrixList)
print(stacked_matrices.shape)
for k in range(stacked_matrices.shape[1]):
for j in range(stacked_matrices.shape[2]):
plt.plot(index, stacked_matrices[:, j, k], label=f"mat[{j},{k}]")
plt.legend()
plt.xlabel("index")
plt.show()
The code produces the image below

I am trying to write a sample user define function that will plot, but having issues

import numpy as np
import matplotlib.pyplot as plt
x=np.array([1,2,3,4,5,6])
def linear(a,b):
return a*x+b
plt.plot(x,linear(a,b))
plt.show()
linear(2,4)
It just gives me the output [6,8,10,12,14,16] but not a plot. I cannot see what's wrong.
You are using return before plot.Change your code to something like this:
import numpy as np
import matplotlib.pyplot as plt
x=np.array([1,2,3,4,5,6])
def linear(a,b):
return a*x+b
plt.plot(x,linear(2,4))
plt.show()

Pass variable to Ipython Widget

I have a simple widget that modifies a plot, here is the definition:
#Plot function
def plf(x,lm,ls):
plt.plot(x[lm:ls],np.sin(x)[lm:ls])
this function takes a list x an plot sin(x), lm and ls controls the number of data that is ploted, the problem is when i try to plot a determinated list of data, for example
list = [1,2,3,4,5,6,7,8,9]
and if i try
interact(plf,x=list,lm=(0,max(x)//2,1),ls=(max(x)//2,max(x),1))
throws me the error:
NameError: name 'x' is not defined
so, how can i define x so it can be any list that i want?
Is this what you are trying to do?
%matplotlib inline
from IPython.html.widgets import interact, fixed
import matplotlib.pyplot as plt
import numpy as np
def plf(x,lm,ls):
plt.plot(x[lm:ls],np.sin(x)[lm:ls])
data = [1,2,3,4,5,6,7,8,9]
max_lm = max(data)//2
max_ls = max(data)
interact(plf,x=fixed(data),lm=(0,max_lm,1),ls=(max_lm, max_ls,1))

pyplot: loglog() with base e

Python (and matplotlib) newbie here coming over from R, so I hope this question is not too idiotic. I'm trying to make a loglog plot on a natural log scale. But after some googling I cannot somehow figure out how to force pyplot to use a base e scale on the axes. The code I have currently:
import matplotlib.pyplot as pyplot
import math
e = math.exp(1)
pyplot.loglog(range(1,len(degrees)+1),degrees,'o',basex=e,basey=e)
Where degrees is a vector of counts at each value of range(1,len(degrees)+1). For some reason when I run this code, pyplot keeps giving me a plot with powers of 2 on the axes. I feel like this ought to be easy, but I'm stumped...
Any advice is greatly appreciated!
When plotting using plt.loglog you can pass the keyword arguments basex and basey as shown below.
From numpy you can get the e constant with numpy.e (or np.e if you import numpy as np)
import numpy as np
import matplotlib.pyplot as plt
# Generate some data.
x = np.linspace(0, 2, 1000)
y = x**np.e
plt.loglog(x,y, basex=np.e, basey=np.e)
plt.show()
Edit
Additionally if you want pretty looking ticks you can use matplotlib.ticker to choose the format of your ticks, an example of which is given below.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
x = np.linspace(1, 4, 1000)
y = x**3
fig, ax = plt.subplots()
ax.loglog(x,y, basex=np.e, basey=np.e)
def ticks(y, pos):
return r'$e^{:.0f}$'.format(np.log(y))
ax.xaxis.set_major_formatter(mtick.FuncFormatter(ticks))
ax.yaxis.set_major_formatter(mtick.FuncFormatter(ticks))
plt.show()
It can also works for semilogx and semilogy to show them in e and also change their name.
import matplotlib.ticker as mtick
fig, ax = plt.subplots()
def ticks(y, pos):
return r'$e^{:.0f}$'.format(np.log(y))
plt.semilogy(Time_Series, California_Pervalence ,'gray', basey=np.e )
ax.yaxis.set_major_formatter(mtick.FuncFormatter(ticks))
plt.show()
Take a look at the image.

Categories