Python3:Plot f(x,y), preferably using matplotlib

2024/9/22 7:32:28

Is there a way, preferably using matplotlib, to plot a 2-variable function f(x,y) in python; Thank you, in advance.

Answer

If You have an expresson for Z

If You have an expression for Z You can generate mesh, and call for surface_plot:

#!/usr/bin/python3import sysimport matplotlib
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3Dimport numpy
from numpy.random import randn, shuffle
from scipy import linspace, meshgrid, arange, empty, concatenate, newaxis, shape# =========================
## generating ordered data:N = 32
x = sorted(randn(N))
y = sorted(randn(N))X, Y = meshgrid(x, y)
Z = X**2 + Y**2# ======================================
## reference picture (X, Y and Z in 2D):fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.jet, linewidth=0)
fig.colorbar(surf)title = ax.set_title("plot_surface: given X, Y and Z as 2D:")
title.set_y(1.01)ax.xaxis.set_major_locator(MaxNLocator(5))
ax.yaxis.set_major_locator(MaxNLocator(6))
ax.zaxis.set_major_locator(MaxNLocator(5))fig.tight_layout()
fig.savefig('3D-constructing-{}.png'.format(N))

Result:

enter image description here

If You don't have an expression for Z

surface_plot function used above only accepts X, Y and Z as 2D arrays. Which is not possible if don't have an expression for Z -- but just have a data stored in a list of lists: [[x1, y1, z1],[x2,y2,z2],...]. In this case You can use plot_trisurf.

In a code below I construct 2D of X, Y and Z, then re-shape the data to have X, Y and Z in 1D, shuffle it, and use plot_trisurf to plot the same data:

#!/usr/bin/python3import sysimport matplotlib
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3Dimport numpy
from numpy.random import randn, shuffle
from scipy import linspace, meshgrid, arange, empty, concatenate, newaxis, shape# =========================
## generating ordered data:N = 128
x = sorted(randn(N))
y = sorted(randn(N))X, Y = meshgrid(x, y)
Z = X**2 + Y**2# =======================
## re-shaping data in 1D:# flat and prepare for concat:
X_flat = X.flatten()[:, newaxis]
Y_flat = Y.flatten()[:, newaxis]
Z_flat = Z.flatten()[:, newaxis]DATA = concatenate((X_flat, Y_flat, Z_flat), axis=1)shuffle(DATA)Xs = DATA[:,0]
Ys = DATA[:,1]
Zs = DATA[:,2]# ====================================================
## plotting surface using X, Y and Z given as 1D data:fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')surf = ax.plot_trisurf(Xs, Ys, Zs, cmap=cm.jet, linewidth=0)
fig.colorbar(surf)title = ax.set_title("plot_trisurf: takes X, Y and Z as 1D")
title.set_y(1.01)ax.xaxis.set_major_locator(MaxNLocator(5))
ax.yaxis.set_major_locator(MaxNLocator(6))
ax.zaxis.set_major_locator(MaxNLocator(5))fig.tight_layout()
fig.savefig('3D-reconstructing-{}.png'.format(N))

Result:

enter image description here

https://en.xdnf.cn/q/119611.html

Related Q&A

Why does my cronjob not send the email from my script? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to repro…

How to delete unsaved tkinker label?

I made this program where I am putting labels on a grid without saving them in a variable. I do this because then I can for loop through a list of classes and get the data from each class in and add th…

Adjust every other row of a data frame

I would like to change every second row of my data frame.I have a df like this:Node | Feature | Indicator | Value | Class | Direction -------------------------------------------------------- 1 | …

Why is the list index out of range?

Im new at programing and Im trying to check a piece of code that keeps giving me this error: t[i] = t[i - 1] + dt IndexError: list index out of rangeThe code is the following: dt = 0.001t = [0] for i i…

Stopping a while loop mid-way - Python

What is the best way to stop a while loop in Python mid-way through the statement? Im aware of break but I thought using this would be bad practice.For example, in this code below, I only want the pro…

Click on element in dropdown with Selenium and Python

With Selenium and Chrome webdriver on MacOS need to click dropdown element. But always have an error that cant find. Have this html code on a page where it located:<select id="periodoExtrato&qu…

Send cv2 video stream for face recognition

Im struggling with a problem to send a cv2 videostream (webcam) to a server (which shall be used later for face recognition). I keep getting the following error for the server: Traceback (most recent c…

Generate all possible lists from the sublist in python [duplicate]

This question already has answers here:How to get the Cartesian product of multiple lists(20 answers)Closed 7 years ago.Suppose I have list [[a, b, c], [d, e], [1, 2]]I want to generate list where on t…

Time/frequency color map in python

Is there in native Python 3.X library or in scipy/numpy/matplolib libraries a function or their short set which could help me to draw a plot similar to this one(?):What would be an efficient way to ac…

ImageMagick is splitting the NASAs [.IMG] file by a black line upon converting to JPG

I have some raw .IMG format files which Im converting to .jpg using ImageMagick to apply a CNN Classifier. The converted images, however have a black vertical line splitting the image into two. The par…