我想使用 matplotlib 制作一个给定 z 函数的 3d 图 [英] I want to use matplotlib to make a 3d plot given a z function

查看:39
本文介绍了我想使用 matplotlib 制作一个给定 z 函数的 3d 图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 z 函数,它接受 x 和 y 参数并返回 z 输出.我想在3d中绘制并设置比例.我如何轻松做到这一点?我花了太多时间浏览文档,但我一次都没有看到这样做的方法.

I have a z function that accepts x and y parameters and returns a z output. I want to plot this in 3d and set the scales. How can I do this easily? I've spent way too much time looking through the documentation and not once do I see a way to do this.

推荐答案

绘图风格取决于您的数据:您是要绘制 3D 曲线(线)、曲面还是散点的点?

The plotting style depends on your data: are you trying to plot a 3D curve (line), a surface, or a scatter of points?

在下面的第一个示例中,我仅使用了x-y平面中均匀分布点的简单网格作为域.通常,首先创建一个xs和ys的域,然后从中计算zs.

In the first example below I've just used a simple grid of evenly spaced points in the x-y plane for the domain. Generally, you first create a domain of xs and ys, and then calculate the zs from that.

此代码应为您提供一个工作示例,供您开始使用:

This code should give you a working example to start playing with:

import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import random

def fun(x, y):
    return x + y

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
n = 10
xs = [i for i in range(n) for _ in range(n)]
ys = list(range(n)) * n
zs = [fun(x, y) for x,y in zip(xs,ys)]

ax.scatter(xs, ys, zs)

ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')

plt.show()

对于曲面,这有点不同,您将网格传入二维数组中的域.这是一个光滑的表面示例:

For surfaces it's a bit different, you pass in a grid for the domain in 2d arrays. Here's a smooth surface example:

import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import random

def fun(x, y):
    return x**2 + y

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x = y = np.arange(-3.0, 3.0, 0.05)
X, Y = np.meshgrid(x, y)
zs = np.array([fun(x,y) for x,y in zip(np.ravel(X), np.ravel(Y))])
Z = zs.reshape(X.shape)

ax.plot_surface(X, Y, Z)

ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')

plt.show()

有关更多示例,请查看文档中的 mplot3d教程.

For many more examples, check out the mplot3d tutorial in the docs.

这篇关于我想使用 matplotlib 制作一个给定 z 函数的 3d 图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆