How to plot this 2D sinusoidal parametric function - python

I have a 2D sinusoidal function and I want to plot its boundary threshold of t=0. Could someone give me a hint on how to do it?
f (x, y) = sin(10x) + cos(4y) − cos(3xy)
x ∈ [0, 1], y ∈ [0, 2], with a boundary threshold of t = 0
The expected plot should look like this: Plot A dashed lines
Actually the function I am referring to is a toy one from paper "Active Learning For Identifying Function Threshold Boundaries"(https://papers.nips.cc/paper/2005/file/8e930496927757aac0dbd2438cb3f4f6-Paper.pdf)
Page 4 of that paper
Update: I tried the following code but apparently it does not give what I want. The top view is a straight line from (0,0) to (1,2), instead of some curves...
ax = plt.axes(projection='3d')
# Data for a three-dimensional line
xline = np.linspace(0, 1, 1000)
yline = np.linspace(0, 2, 1000)
zline = np.sin(10*xline)+np.cos(4*yline)-np.cos(3*xline*yline)
ax.plot3D(xline, yline, zline, 'gray')

Welcome to stackoverflow. Your math is wrong. Your function f is a function of two variables, f(x, y). Hence you need to evaluate it on a grid (all combinations of valid x and y values), if you want to find the solutions for f = 0 computationally. Your code is currently evaluating f only on the y = 2x axis (hence the "straight line from (0,0) to (1, 2) in top-down view").
import numpy as np
import matplotlib.pyplot as plt
def f(x, y):
return np.sin(10*x)+np.cos(4*y)-np.cos(3*x*y)
x = np.arange(0, 1, 1e-3)
y = np.arange(0, 2, 1e-3)
XX, YY = np.meshgrid(x, y)
ZZ = f(XX, YY)
plt.contour(XX, YY, ZZ, levels=[0.])
plt.show()

Related

How to Draw a Normal Line Plot in a Quiver PLot

I have a quiver plot that plots (1, f(x)) for each (x,y) whereas f(x) = exp(-(x-4)^2)
import numpy as np
import matplotlib.pyplot as plt
# Define domain
x = np.linspace(0, 8, 40)
y = np.linspace(0, 2, 40)
x, y = np.meshgrid(x, y)
# Compute direction using the derivative
def dv(x):
y = np.exp(-2*(x-4)**2)
n = -2*(x-4)*np.exp(-2*(x-4)**2)
return y*n
# Define functions
u = 1
v = dv(x)
# Plot
fig = plt.figure() # a new figure window
ax = fig.add_subplot(1, 1, 1) # specify (nrows, ncols, axnum)
ax.quiver(x, y, u, v, fn(x))
#ax.plot(x, fn(x))
fig.show()
It looks like this
Now I want to also plot a line that starts at e.g. (x=0, y=2) and follows the vector field/flow i.e. basically plot f(x) for a fixed y. I tried to do so by sharing the axes with ax.plot(), but that didn't work for a reason unknown to me.
The ultimate goal is to show how a particle would move if we dropped it somewhere at the start. I know there is streamplot() but I really want a vector field like this because I wanna relate the Eulerian and the Lagragian point of view.

Plotting piecewise contour graph in Python

I want to plot a piecewise function in Python where there are two variables x and y. This means I would need some kind of contour graph. In Matlab one may use
syms x y
eq1 = 0.1*(x/2)^2-0.3*(y/4)^2;
eq2 = 0.15*(x/3)^2-0.25*(y/2)^2;
ezplot(eq1,[-5 5 -10 10]);
hold on
ezplot(eq2,[-4 4 -5 5]);
where ezplot plots eq1 = 0 over xmin < x < xmax and ymin < y < ymax. Is there any (simple) equivalent function(s) in Python?
I have looked at the solutions in this post. Their problem only involves one variable x so it's not helpful in my case.
You can separate the different pieces by using numpy's masked array.
At first define your functions, the x and y ranges and their 2D versions for the contour plot:
import numpy as np
import matplotlib.pyplot as plt
from numpy.ma import masked_array as marr
def eq1(x, y):
return 0.1*(x/2)**2-0.3*(y/4)**2
def eq2(x, y):
return 0.15*(x/3)**2-0.25*(y/2)**2
x = np.linspace(-5, 5, 101)
y = np.linspace(-10, 10, 201)
xx, yy = np.meshgrid(x, y)
Now we need a 2D mask (or some, depending on the number of pieces of the piecewise function) to separate definition ranges of the different pieces of the function:
maskx = ((xx>=-4) * (xx<=4))
masky = ((yy>=-5) * (yy<=5))
mask = maskx * masky
This can be applied to different masked arrays:
res1 = marr(eq1(xx, yy), mask)
res2 = marr(eq2(xx, yy), ~mask)
Plotting a masked array leaves all the area blank where the mask is True:
fig, axs = plt.subplots(1, 2, sharey=True)
axs[0].contour(xx, yy, res1)
axs[0].contour(xx, yy, res2)
axs[0].set_title('contour')
axs[1].contourf(xx, yy, res1)
axs[1].contourf(xx, yy, res2)
axs[1].set_title('contourf')

Contour plot in python [duplicate]

This question already has answers here:
Make contour of scatter
(3 answers)
Closed 5 years ago.
I have 3 lots of data. These are x and y values as well as a temperature value for each xy point. I would like to plot each point and interpolate the area between points to get a continuous surface. The issue I have is specifying the temperature values. I can't get it to work with an equal number of x,y and z (temperature) values and all the examples I can find online use a function of x and y to create z or have z values for every point on an xy grid.
Is there a simple way to do this?
import numpy as np
import matplotlib.pyplot as plt
fig, axs = plt.subplots()
x = np.linspace(0, 1, 100)
y = np.linspace(0,1,100)
X, Y = np.meshgrid(x, y)
#Z = np.sin(X)*np.sin(Y) # want to specify not an equation
Z = np.linspace(1,2,100)
levels = np.linspace(-1, 1, 40)
cs = axs.contourf(X, Y, Z, levels=levels)
fig.colorbar(cs, ax=axs, format="%.2f")
plt.show()
Update:
Here is what I have so far. I still need to work out a good method to fill in the area between points. Does anyone have any ideas?
import numpy as np
import matplotlib.pyplot as plt
fig, axs = plt.subplots()
# create a grid in the correct shape / size
x = np.linspace(0, 1, 3)
y = np.linspace(0,1,3)
X, Y = np.meshgrid(x, y)
# specify and change the relevent areas
y = [1,2,0] # location of point in x direction
x =[2,1,1] #location of point in y direction
z = [40,30,20] #temperature
Z = np.arange(1,10).reshape((3,3))
Z[y,x] = z
levels = np.linspace(0, 40, 40)
cs = axs.contourf(X, Y, Z, levels=levels)
fig.colorbar(cs, ax=axs, format="%.2f")
plt.show()
The reason people use a function of x and y is because your Z value has to be a function of x and y. In your test code Z is 1D but it needs to be 2D to plot the contours.
If you have Z (temperature) values that have the same shape as your x and y coordinates then it should work.
x = np.linspace(0, 1, 100)
y = np.linspace(0,1,100)
X, Y = np.meshgrid(x, y)
#Z = np.sin(X)*np.sin(Y) # want to specify not an equation
Z = np.linspace(1,2,100)
print X.shape
print Z.shape
(100L,100L)
(100L)

How to change the axis dimension from pixel to length in matplotlib? is there any code in general?

Since the complete simulation is to big to post it right here only the code to plot the spectrum is given (I think this is enough)
d = i.sum(axis=2)
pylab.figure(figsize=(15,15))
pylab = imshow(d)
plt.axis('tight')
pylab.show()
This spectrum is given in pixel. But I would like to have this in the units of length. I will hope you may give me some advices.
Do you mean that you want axis ticks to show your custom dimensions instead of the number of pixels in d? If yes, use the extent keyword of imshow:
import numpy
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
d = numpy.random.normal(size=(20, 40))
fig = plt.figure()
s = fig.add_subplot(1, 1, 1)
s.imshow(d, extent=(0, 1, 0, 0.5), interpolation='none')
fig.tight_layout()
fig.savefig('tt.png')
I'm guess a bit at what your problem is, so let's start by stating my interpretation/ You have some 2D data d that you plot using imshow and the units on the x and y axes are in the number of pixels. For example in the following we see the x axis labelled from 0 -> 10 for the number of data points:
import numpy as np
import matplotlib.pyplot as plt
# Generate a fake d
x = np.linspace(-1, 1, 10)
y = np.linspace(-1, 1, 10)
X, Y = np.meshgrid(x, y)
d = np.sin(X**2 + Y**2)
plt.imshow(d)
If this correctly describes your issue, then the solution is to avoid using imshow, which is designed to plot images. Firstly this will help as imshow attemps to interpolate to give a smoother image (which may hide features in the spectrum) and second because it is an image, there is no meaningful x and y data so it doesn't plot it.
The best alternative would be to use plt.pcolormesh which generate a psuedocolor plot of a 2D array and takes as arguments X and Y, which are both 2D arrays of points to which the values of d correspond.
For example:
# Generate a fake d
x = np.linspace(-1, 1, 10)
y = np.linspace(-1, 1, 10)
X, Y = np.meshgrid(x, y)
d = np.sin(X**2 + Y**2)
plt.pcolormesh(X, Y, d)
Now the x and y values correspond to the values of X and Y.

PyLab contourf with experimental data

I'm trying to understand and adapt the following code:
import numpy as np
def f(x,y):
return (1 - x / 2 + x**5 + y**3) * np.exp(-x**2 -y**2)
n = 256
x = np.linspace(-3, 3, n)
y = np.linspace(-3, 3, n)
X,Y = np.meshgrid(x, y)
pl.axes([0.025, 0.025, 0.95, 0.95])
pl.contourf(X, Y, f(X, Y), 8, alpha=.75, cmap=pl.cm.hot)
C = pl.contour(X, Y, f(X, Y), 8, colors='black', linewidth=.5)
pl.clabel(C, inline=1, fontsize=10)
pl.xticks(())
pl.yticks(())
pl.show()
Here we have a set of points (x,y) and a value for each point, computed with f(x,y)
Now, I have a set of computational results in the form of x;y;output in a txt output file that I read with csv module for example. The point is that I'm not understanding the data types here, probably the meshgrid. Let's say that each point is a key key in a dictionary FH_DICT so as FH_DICT[key] will play the role of f(x,y) in the code above. But I don't know how to implement it, as the output value for each point it is not easy to express as a mathematical function.
Thanks for your time.

Categories