numpy and matplot - plotting on the same graph while one element changes - python

I'm trying to create a graph with k_b as the x-value and delta_P as the y-value. I want to plot k_b against delta_P but S=3 for one curve and S=0.1 for another curve. However, I want the two lines to be on the same graph. Does anyone have any advice on how to do that? Below is what I have for S=3 and it works.
def rocproduct(k_cat,E0,S,k_b,k_f):
return k_cat*E0*S/((k_b/k_f)+S)
import numpy as np
import matplotlib.pyplot as plt
k_cat=0.1;E0=1;k_f=0.3;S=3
k_b=np.array([0.01,0.1,0.2,0.5,1,1.5,2,5,10])
delta_P=rocproduct(k_cat,E0,S,k_b,k_f)
plt.ylabel('rate of change of product')
plt.xlabel('kb')
plt.plot(k_b,delta_P)

Just call rocproduct for S=0.1 and plot it again
import numpy as np
import matplotlib.pyplot as plt
# Parameters
k_cat=0.1
E0=1
k_f=0.3
S=3
# Function for data
def rocproduct(k_cat,E0,S,k_b,k_f):
return k_cat*E0*S/((k_b/k_f)+S)
# Data to plot
k_b=np.array([0.01,0.1,0.2,0.5,1,1.5,2,5,10])
delta_P_1=rocproduct(k_cat,E0,S,k_b,k_f)
S = 0.1
delta_P_2=rocproduct(k_cat,E0,S,k_b,k_f)
# Plotting
plt.ylabel('rate of change of product')
plt.xlabel('kb')
plt.plot(k_b,delta_P_1)
plt.plot(k_b, delta_P_2)
plt.show()

Related

How to make minimum point can see from above of surface plot?

I want to plot the surface graph and minimum point as follows:
I have tried to make python code:
import sympy
import numpy
from numpy import linalg
from numpy import linspace
from sympy import lambdify
import matplotlib.pyplot as plt
from matplotlib import cm
x1,x2=sympy.symbols('x1 x2')
f=x1**2-x1*x2-4*x1+x2**2-x2
lam_f = lambdify([x1,x2], f, modules=['numpy'])
x1value=linspace(-6,6,50)
x2value=linspace(-6,6,50)
x1value, x2value = numpy.meshgrid(x1value, x2value)
fvalue=lam_f(x1value,x2value)
fig, ax = plt.subplots(subplot_kw={"projection": "3d"})
surf = ax.plot_surface(x1value, x2value, fvalue, cmap=cm.jet,linewidth=0, antialiased=False,label="$f(x_1,x_2)$")
ax.set_xlabel('$x_1$')
ax.set_ylabel('$x_2$')
ax.set_zlabel('$f(x_1,x_2)$')
ax.scatter(3,2,-7,color="cyan",s=50,marker="s",zorder=2,linewidths=2)
plt.show()
The minimum point cannot see from above, but from below we can see the minimum point.
I want minimum point can see from above as the first picture. How to make it?

How to plot a smooth curve in python for a list of values?

I have created a list of values of Shannon entropy for a pair of multiple sequence aligned sequences. While plotting the values I get a simple plot. I want to plot a smooth curve over the lines. Can anyone suggest to me what will be the right way to process it? BAsically I want to plot a smooth curve that touches the tip of every bar and goes to zero where the "y axis value" is zero.
link for image: [1]: https://i.stack.imgur.com/SY3jH.png
#importing the relevant packages
import math
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from scipy.interpolate import make_interp_spline
from Bio import AlignIO
import warnings
warnings.filterwarnings("ignore")
#function to calculate the Shannon Entropy of a MSA
# H = -sum[p(x).log2(px)]
def shannon_entropy(list_input):
unique_aa = set(list_input)
M = len(list_input)
entropy_list = []
# Number of residues in column
for aa in unique_aa:
n_i = list_input.count(aa)
P_i = n_i/float(M)
entropy_i = P_i*(math.log(P_i,2))
entropy_list.append(entropy_i)
sh_entropy = -(sum(entropy_list))
#print(sh_entropy)
return sh_entropy
#importing the MSA file
#importing the clustal file
align_clustal1 =AlignIO.read("/home/clustal.aln", "clustal")
def shannon_entropy_list_msa(alignment_file):
shannon_entropy_list = []
for col_no in range(len(list(alignment_file[0]))):
list_input = list(alignment_file[:, col_no])
shannon_entropy_list.append(shannon_entropy(list_input))
return shannon_entropy_list
clustal_omega1 = shannon_entropy_list_msa(align_clustal1)
# Plotting the data
plt.figure(figsize=(18,10))
plt.plot(clustal_omega1, 'r')
plt.xlabel('Residue', fontsize=16)
plt.ylabel("Shannon's entropy", fontsize=16)
plt.show()
Edit 1:
Here is what my graph looks like after implementing the "pchip" method. link for the pchip output: https://i.stack.imgur.com/hA3KW.png
pchip monotonic spline output
One approach would be to use PCHIP interpolation, which will give you the monotonic curve with the required behaviour for zero values on the y-axis.
We can't run your exact code example on our machines because you point to a local Clustal file in your 'home' directory.
Here's a simple working example, with link to output image:
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import pchip
mylist = [10,0,0,0,0,9,9,0,0,0,11,11,11,0,0]
mylist_np = np.array(mylist)
samples = np.array(range(len(mylist)))
xnew = np.linspace(samples.min(), samples.max(), 100)
plt.plot(xnew,pchip(samples, mylist_np )(xnew))
plt.show()

how to calculate phase space of velocity and draw a scatter plot in python?

I have a vector for velocity of a time series. for example :
u=[100,120,150,115,130,115,105,103,108,132,135,121]
now I need to calculate Δu and then draw a scatter plot.
something like the picture below.
how can I do that?
import numpy as np
import matplotlib.pyplot as plt
u = np.array([100,120,150,115,130,115,105,103,108,132,135,121])
du = u[1:] - u[:-1] # the difference between the current and the prior velocity
plt.scatter(u[1:],du)
plt.show()
Assuming Δu = u[i] - u[i-1], It is obvious you should use this formula for u[1:].
So just simply use these lines of codes:
from numpy import array
import matplotlib.pyplot as plt
u = aray(u)
del_u = u[1:] - u[:-1] # This line let you use that formula for all numbers in array except first one.
plt.scatter(u[1:], del_u)
plt.show()

How does `matplotlib` adjust plot to figure size?

How does matplotlib ensure that a dataset can be within plot with specified size.
How do i from a plot stored as numpy, How do i read the color of the pixels illustration a datapoint (0,4) - in the plot.
example:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
from PIL import Image
import librosa
import librosa.display
from matplotlib import cm
fig = plt.figure(figsize=(12,4))
min = -1.828067
max = 22.70058
data = np.random.uniform(low=min, high=max, size=(474,40))
librosa.display.specshow(data.T,sr=16000,x_axis='frames',y_axis='mel',hop_length=160,cmap=cm.jet)
plt.show()
raw_input("sadas")
convert = plt.get_cmap(cm.jet)
numpy_output_static = convert(data.T)
plt.imshow(numpy_output_static, aspect = 'auto')
plt.show()
raw_input("asds")
First plot being :
Second plot being:
so the first has been resized to plot size 12,4 where the last basically plots the same data but just using the data shape as size... how do i change that?
Librosa just performs pcolormesh according to the GitHub source code
You need to define another figure with its own size for the second figure.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
from PIL import Image
import librosa
import librosa.display
from matplotlib import cm
fig = plt.figure(figsize=(12,4))
min = -1.828067
max = 22.70058
data = np.random.uniform(low=min, high=max, size=(474,40))
librosa.display.specshow(data.T,sr=16000,x_axis='frames',y_axis='mel',hop_length=160,cmap=cm.jet)
plt.show()
raw_input("sadas")
convert = plt.get_cmap(cm.jet)
numpy_output_static = convert(data.T)
fig = plt.figure(figsize=(12,4))
plt.imshow(numpy_output_static, aspect = 'auto')
plt.show()
raw_input("asds")

How to locate the median in a (seaborn) KDE plot?

I am trying to do a Kernel Density Estimation (KDE) plot with seaborn and locate the median. The code looks something like this:
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
sns.set_palette("hls", 1)
data = np.random.randn(30)
sns.kdeplot(data, shade=True)
# x_median, y_median = magic_function()
# plt.vlines(x_median, 0, y_median)
plt.show()
As you can see I need a magic_function() to fetch the median x and y values from the kdeplot. Then I would like to plot them with e.g. vlines. However, I can't figure out how to do that. The result should look something like this (obviously the black median bar is wrong here):
I guess my question is not strictly related to seaborn and also applies to other kinds of matplotlib plots. Any ideas are greatly appreciated.
You need to:
Extract the data of the kde line
Integrate it to calculate the cumulative distribution function (CDF)
Find the value that makes CDF equal 1/2, that is the median
import numpy as np
import scipy
import seaborn as sns
import matplotlib.pyplot as plt
sns.set_palette("hls", 1)
data = np.random.randn(30)
p=sns.kdeplot(data, shade=True)
x,y = p.get_lines()[0].get_data()
#care with the order, it is first y
#initial fills a 0 so the result has same length than x
cdf = scipy.integrate.cumtrapz(y, x, initial=0)
nearest_05 = np.abs(cdf-0.5).argmin()
x_median = x[nearest_05]
y_median = y[nearest_05]
plt.vlines(x_median, 0, y_median)
plt.show()

Categories

Resources