简体   繁体   English

如何在python中绘制f(x,y)= sqrt(2x-y)

[英]how to plot in python f(x,y)=sqrt(2x-y)

I'm trying to plot the following multivariable f(x,y)=sqrt(2x-y) but can't make it work with numpy and matplotlib. 我正在尝试绘制以下多变量f(x,y)= sqrt(2x-y),但无法使其与numpy和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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM