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

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?

Related

Fourier series animation effect using by python ArtistAnimation

I'm studying about Fourier Series with python.
I drew it with cosine and sine function.
My code is like this.
import numpy as np
import matplotlib.pyplot as plt
from sympy import *
x = Symbol('x')
fx=0
j=10
for i in range(1,j):
fx=fx+(2)/(np.pi*i)*(1-cos(i*np.pi))*(sin(i*x))
y_func=lambdify(x, fx, "numpy")
x_val=np.linspace(-np.pi,np.pi,315)
y_val=y_func(x_val)
plt.plot(x_val,y_val)
plt.show()
I could get the correct graph.
And I tried to make the graph into animaion effect like this gif file.
enter image description here
I wrote the code like below using by ArtistAnimation , but I couldn't get the animation.
How can i get the animation?
import numpy as np
import matplotlib.pyplot as plt
from sympy import *
from matplotlib.animation import ArtistAnimation
x = Symbol('x')
fx=0
j=10
img=[]
fig, ax=plt.subplots(constrained_layout=True)
for i in range(1,j):
fx=fx+(2)/(np.pi*i)*(1-cos(i*np.pi))*(sin(i*x))
y_func=lambdify(x, fx, "numpy")
x_val=np.linspace(-np.pi,np.pi,315)
y_val=y_func(x_val)
fs=plt.plot(x_val,y_val)
img.append([fs])
anim=ArtistAnimation(fig,img,interval=5)
anim.save("Fourier_Series01.gif",fps=24)
I tried to make the code with ArtistAnimation
Thank you for your answer

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

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()

How plot many points 3d in matplotlib

I am trying to plot 8000 points in three dimensions (x,y,z) of a terrain with matplotlib using the function contourf when I run the code I get the error
'OverflowError: In draw_path_collection: Exceeded cell block limit'
I tried to solve this with "mpl.rcParams['agg.path.chunksize'] = 20000"
but this did not resolve the issue. Here is my code
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from scipy.interpolate import griddata
import pandas as pd
import matplotlib as mpl
datos = pd.read_csv('zrh_terrain.txt', header =0)
dats=500
mpl.rcParams['agg.path.chunksize'] = 20000
X=datos.iloc[0:dats,0].values
Y=datos.iloc[0:dats,1].values
Z=datos.iloc[0:dats,2].values
dt_bar=np.linspace(Z.min(),Z.max(),10)
xi,yi= np.meshgrid(X,Y)
zi = griddata((X,Y),Z,(xi,yi),method='nearest')
plt.contourf(xi,yi,zi,extend='both',vmin=dt_bar[0],vmax=dt_bar[-1],
cmap=cm.terrain)

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