Probability surface plot matplotlib - python

I have 2d values of x and y which span from x - [ 1 , 5 ] and y - [0.1 - 0.5]
How can I plot the 3d surface where the axis are x , y and P(y) in matplotlib ?
I found out the code for doing so in matlab on net but I am unable to understand it and consequently convert it into matplotlib... ( the range of values is completely different for below written code as to what I require )
mu = [1 -1]; Sigma = [.9 .4; .4 .3];
[X1,X2] = meshgrid(linspace(-1,3,25)', linspace(-3,1,25)');
X = [X1(:) X2(:)];
p = mvnpdf(X, mu, Sigma);
surf(X1,X2,reshape(p,25,25));
Can someone help me out in doing the exact same thing for matplotlib ( plot_surface perhaps ? )

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.mlab as mlab
import numpy as np
def P(X, Y):
return mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
fig = plt.figure()
ax = fig.gca(projection = '3d')
jet = plt.get_cmap('jet')
x = np.linspace(-2, 2, 60)
y = np.linspace(-2, 2, 60)
X, Y = np.meshgrid(x, y)
Z = P(X, Y)
surf = ax.plot_surface(X, Y, Z, rstride = 1, cstride = 1, cmap = jet, linewidth = 0)
ax.set_zlim3d(0, Z.max())
plt.show()
yields

Related

Plotting inequalities in Python

I want to shade the area of the XY plane where Y<18 x^2.
This is my code:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-.25, .25, 25)
y = np.linspace(0, 1, 20)
X,Y = np.meshgrid(x, y)
Z = masqarr(1,X, Y)
plt.imshow( (Y< 18*X**2).astype(float) ,
extent=(X.min(),X.max(),Y.min(),Y.max()),origin="lower", cmap="Greys", alpha = 0.3, aspect='auto', interpolation = 'hanning');
However, the output I get produces a plot with plateau as in:
How can I gat a proper smooth plot?
This is a resolution problem, you are defining your axes with too few poitns. I tried this:
import numpy as np
import matplotlib.pyplot as plt
resolution = 200
x = np.linspace(-.25, .25, resolution)
y = np.linspace(0, 1, resolution)
X,Y = np.meshgrid(x, y)
plt.imshow( (Y< 18*X**2).astype(float) ,
extent=(X.min(),X.max(),Y.min(),Y.max()),origin="lower", cmap="Greys", alpha = 0.3, aspect='auto', interpolation = 'hanning');
plt.show()
resolution = 25
resolution = 100
resolution = 200

How to extend matplotlib colorbar for contourf plot?

The following code produces a contourf plot.
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0,10)
X, Y = np.meshgrid(x, x)
F = np.sin(X)*np.cos(Y)
v = np.linspace(-2, 2,10)
plt.contourf(X, Y, F, 500)
cb = plt.colorbar()
F ranges from -1 to 1 so my colorbar has these as its minimum and maximum values. I want the colorbar to range from -2 to 2. I have tried to set the ticks to range from -2 to 2 however this does not work. Any suggestions?
works if you create the colorbar manually:
import numpy as np
import matplotlib as mpl
x = np.linspace(0,10)
X, Y = np.meshgrid(x, x)
F = np.sin(X)*np.cos(Y)
v = np.linspace(-2, 2,10)
f, ax = plt.subplots()
cont = ax.contourf(X, Y, F, 500, vmin=-2, vmax=2, ticks=v)
cax, _ = mpl.colorbar.make_axes(ax)
cbar = mpl.colorbar.ColorbarBase(cax, cmap=cont.cmap, norm=cont.norm)
cbar.set_ticks([v.min(), *np.linspace(F.min(), F.max(), 11), v.max()])

Overlapping surfaces with Matplotlib

Basically I have two graphs and I want to plot them both without overlapping one over the other.
from matplotlib import cm
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
X = np.arange(0, 5, 0.05)
Y = np.arange(0, 5, 0.05)
X, Y = np.meshgrid(X, Y)
Z = (np.sin(X) / X) + 2
X1 = np.arange(0, 5, 0.05)
Y1 = np.arange(0, 5, 0.05)
X1, Y1 = np.meshgrid(X1, Y1)
Z1 = (X / X) + 1
ax.plot_surface(X, Y, Z, alpha = 1, rstride=10, cstride=10, cmap=cm.autumn,linewidth=0.5, antialiased=True, zorder = 0.3)
ax.plot_surface(X, Y, Z1, alpha = 1, rstride=10, cstride=10, cmap=cm.winter, linewidth=0.5, antialiased=True, zorder = 0.5)
plt.show()
We can see here that we have two graphs However when viewed at 90 degrees
Why does this happen and how to proceed?

Plotting surface - enhacing the output

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
def figure():
fig = plt.figure()
axes = fig.gca(projection='3d')
x = np.arange(-1.5, 1.5, 0.1)
y = np.arange(-1.5, 1.5, 0.1)
x, y = np.meshgrid(x, y)
f = lambda x, y: 1/np.log(y - (x-1)**0.5)
axes.plot_wireframe(x, y, f(x, y))
plt.show()
figure()
How can I "zoom" in to the figure (make it appear larger)?
Is there a way to make the figure look smoother when using axes.plot_surface instead?
In this scenario, I would prefer np.linspace over np.arange.
Many of the function values in your range are complex. Those values cannot be displayed. Here I use axes.set_xlim and axes.set_ylim to zoom into the real part of your function.
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
def figure():
fig = plt.figure(figsize=(8,6))
axes = fig.gca(projection='3d')
x = np.linspace(-1.5, 1.5, 100)
y = np.linspace(-1.5, 1.5, 100)
x, y = np.meshgrid(x, y)
f = lambda x, y: 1/np.log(y - (x-1)**0.5)
axes.plot_wireframe(x, y, f(x, y))
axes.set_xlim(1,1.5)
axes.set_ylim(0,1.5)
figure()

axis limits for scatter plot not holding in matplotlib

I am trying to overlay a scatter plot onto a contour plot using matplotlib, which contains
plt.contourf(X, Y, XYprof.T, self.nLevels, extent=extentYPY, \
origin = 'lower')
if self.doScatter == True and len(xyScatter['y']) != 0:
plt.scatter(xyScatter['x'], xyScatter['y'], \
s=dSize, c=myColor, marker='.', edgecolor='none')
plt.xlim(-xLimHist, xLimHist)
plt.ylim(-yLimHist, yLimHist)
plt.xlabel(r'$x$')
plt.ylabel(r'$y$')
What ends up happening is the resulting plots extend to include all of the scatter points, which can exceed the limits for the contour plot. Is there any way to get around this?
I used the following example to try and replicate your problem. If left to default, the range for x and y was -3 to 3. I input the xlim and ylim so the range for both was -2 to 2. It worked.
import numpy as np
import matplotlib.pyplot as plt
from pylab import *
# the random data
x = np.random.randn(1000)
y = np.random.randn(1000)
fig = plt.figure(1, figsize=(5.5,5.5))
X, Y = meshgrid(x, y)
Z1 = bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
Z2 = bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
Z = 10 * (Z1 - Z2)
origin = 'lower'
CS = contourf(x, y, Z, 10, # [-1, -0.1, 0, 0.1],
cmap=cm.bone,
origin=origin)
title('Nonsense')
xlabel('x-stuff')
ylabel('y-stuff')
# the scatter plot:
axScatter = plt.subplot(111)
axScatter.scatter(x, y)
# set axes range
plt.xlim(-2, 2)
plt.ylim(-2, 2)
show()

Categories