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()
Related
Very simple, if I plot x^2+y^2=z it makes this shape on python it will make this shape:
When I would like to plot it this way:
Below is my code, I am new so I copied it from the internet and have changed the line with the function to plot.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-4*np.pi,4*np.pi,50)
y = np.linspace(-4*np.pi,4*np.pi,50)
z = x**2+y**2
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot(x,y,z)
plt.show()
Also, how do I make it more high definition and smooth, this is a graph of z=sin(x)
You need to define a 2D mathematical domain with numpy.meshgrid, then you can compute the surface on that domain:
X, Y = np.meshgrid(x, y)
Z = X**2 + Y**2
In order to increase the smoothness of the surface, you have in increase the number of point N you use to compute x and y arrays:
Complete code
import matplotlib.pyplot as plt
import numpy as np
N = 50
x = np.linspace(-4*np.pi, 4*np.pi, N)
y = np.linspace(-4*np.pi, 4*np.pi, N)
X, Y = np.meshgrid(x, y)
Z = X**2 + Y**2
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(X, Y, Z)
plt.show()
I want to adjust colobar scale from my current figure1 to the desired figure2 !!
My colorbar scale range is -1 to 1, but I want it in exponential form and for that I tried levels = np.linspace(-100e-2,100e-2) as well, but it also doesn't give the desired scale2
import xarray as xr
import numpy as np
import matplotlib.pyplot as plt
ds = xr.open_dataset('PL_Era_Tkt.nc')
wp = ds.w.mean(dim=['longitude','latitude']).plot.contourf(x='time',cmap='RdBu',add_colorbar=False,extend='both')
wpcb = plt.colorbar(wp)
wpcb.set_label(label='Pa.s${^{-1}}$',size=13)
plt.gca().invert_yaxis()
plt.title('Vertical Velocity',size=15)
My current scale
My desired scale
Since the data is not presented, I added normalized color bars with the data from the graph sample here. I think the color bar scales will also be in log format with this setup. Please note that the data used is not large, so I have not been able to confirm this.
%matplotlib inline
import matplotlib.pyplot as plt
import matplotlib as mpl
import matplotlib.ticker as ticker
import numpy as np
plt.style.use('seaborn-white')
def f(x, y):
return np.sin(x) ** 10 + np.cos(10 + y * x) * np.cos(x)
x = np.linspace(0, 5, 50)
y = np.linspace(0, 5, 40)
X, Y = np.meshgrid(x, y)
Z = f(X, Y)
fig, ax = plt.subplots()
ax.contourf(X, Y, Z, 20, cmap='RdGy')
cmap = mpl.cm.RdGy
norm = mpl.colors.Normalize(vmin=-1, vmax=1.0)
fig.colorbar(mpl.cm.ScalarMappable(norm=norm, cmap=cmap),
ax=ax, orientation='vertical', label='Some Units', extend='both', ticks=ticker.LogLocator())
plt.show()
I trying to plot a graph of a function f(x, y) = x**x*y, but I'm getting an error:
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
def f(x,y):
return x**x*y
x = np.arange(-4.0, 4.0, 0.1)
y = np.arange(-4.0, 4.0, 0.1)
z = f(x, y)
X, Y, Z = np.meshgrid(x, y, z)
fig = plt.figure()
ax = Axes3D(fig)
ax.plot_surface(X, Y, Z)
plt.xlabel('x')
plt.ylabel('y')
plt.show()
First error is:
/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:2: RuntimeWarning: invalid value encountered in power
And the second is:
ValueError: Argument Z must be 2-dimensional.
You can try:
X, Y = np.meshgrid(x, y)
Z = f(X, Y)
The meshgrid function returns coordinate matrices from coordinate vectors.. Then, you can apply the function and plot it.
For the "RuntimeWarning: invalid value encountered in power" warning, that is related to the decimal power on numpy objects. Please have a look at this topic NumPy, RuntimeWarning: invalid value encountered in power for more details.
Full code:
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
def f(x,y):
return x**x*y
x = np.arange(-4.0, 4.0, 0.1)
y = np.arange(-4.0, 4.0, 0.1)
X, Y = np.meshgrid(x, y)
Z = f(X, Y)
fig = plt.figure()
ax = Axes3D(fig)
ax.plot_surface(X, Y, Z)
plt.xlabel('x')
plt.ylabel('y')
plt.show()
Output:
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()])
I'm trying to plot the following multivariable f(x,y)=sqrt(2x-y)
but can't make it work with numpy and matplotlib.
I've been trying by defining function but still cant makee it work
from numpy import exp,arange
from pylab import meshgrid,cm,imshow,contour,clabel,colorbar,axis,title,show
from math import sqrt
# the function that I'm going to plot
def z_func(x,y):
return (sqrt(2*x - y))
X,Y = meshgrid(x, y) # grid of point
Z = z_func(X, Y) # evaluation of the function on the grid
im = imshow(Z,cmap=cm.RdBu) # drawing the function
# adding the Contour lines with labels
cset = contour(Z,arange(-1,1.5,0.2),linewidths=2,cmap=cm.Set2)
clabel(cset,inline=True,fmt='%1.1f',fontsize=10)
colorbar(im) # adding the colobar on the right
# latex fashion title
title('my plot')
show()
You need to have more data in order to plot the entire function.
Look at the following code as a reference
import numpy as np
import math
import matplotlib.pyplot as plt
def z_func(x,y):
return (math.sqrt(2*x - y))
x = [10,20,30,40,50]
y =[2,4,6,8,11]
Z = []
for i in range(len(x)):
Z.append(z_func(x[i],y[i]))
plt.plot(Z)
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib import cm
import numpy as np
# the function that I'm going to plot.
# Vectorize so we don't need to loop through
# grid points.
#np.vectorize
def z_func(x, y):
return (np.sqrt(2*x - y))
# define the range where you evaluate
# the function
extent = (0, 10, 0, 10)
x = np.arange(0, 10.1, .1)
y = np.arange(0, 10.1, .1)
# create grid
X, Y = np.meshgrid(x, y)
# evaluate over grid
Z = z_func(X, Y)
# plot contour image
fig = plt.figure()
im = plt.imshow(Z, origin='image', cmap=cm.RdBu, extent=extent)
cset = plt.contour(Z, np.arange(-1,1.5,0.2),linewidths=2,cmap=cm.Set2, extent=extent)
plt.clabel(cset,inline=True, fmt='%1.1f',fontsize=10)
plt.colorbar(im)
plt.show()