首页 > 解决方案 > 在 3D 数据中绘制函数

问题描述

使用下面的代码,我创建了要在图中绘制的三维数据pcolormesh

n = 100 # size
_min, _max = -10, 10

# generate 2 2d grids for the x & y bounds
x, y = np.meshgrid(np.linspace(_min, _max, n), np.linspace(_min, _max, n))

# generate z values with random noise
z = np.array([np.zeros(n) for i in range(n)])

for i in range(len(z)): 
    z[i] = z[i] + 0.1 * np.random.randint(0,3, size=len(z[i]))

# plotting
fig, ax = plt.subplots()
c = ax.pcolormesh(x, y, z, cmap='RdBu', vmin=-1, vmax=1)

ax.set_title('pcolormesh')

plt.plot([5,5,-2.5], [5,-5,5], color='darkblue', marker='o', markersize=15, linewidth=0) # dots (outer)
plt.plot([5,5,-2.5], [5,-5,5], color='lightblue', marker='o', markersize=10, linewidth=0) # dots (inner)

plt.grid(b=True) # background grid

# set the limits of the plot to the limits of the data
ax.axis([_min, _max, _min, _max])
fig.colorbar(c, ax=ax)

plt.show()

这给出了一个图像:

这个

但是,我现在想根据特定功能更改z特定x/y组合的值,例如由(x-5)^2 + (y+5)^2 = 1. 我想更改数据(!)然后绘制它。

“目标”是生成如下图像的数据: 在此处输入图像描述

我可以对这些函数进行试验,主要是关于根据我无法弄清楚z的形式的数学函数改变值的逻辑。z = f(x, y)

它将遵循(伪代码逻辑) if the x / y combination of a point is on the function f(x, y): add the value c to the initial z value:.

有人可以指出我如何实现这一点吗?我尝试了多次,但无法弄清楚... :( 非常感谢提前!!!

注意:早期版本不精确。尽管似乎数据操作是问题,但它错误地将其解释为绘图问题。为此道歉!

标签: python

解决方案


你只需要绘制一个函数,以同样的方式。

用这些线我在你的情节上绘制一个函数。

# Create the independent points of your plot
x = np.arange(0., 5., 0.2)

# Generate your dependent variables
y = np.exp(x)

# Plot your variables
plt.plot(x, y)

然后,您可以多次执行此操作。

在您的完整示例中,它看起来像这样:

import numpy as np
import matplotlib.pyplot as plt

n = 100  # size
_min, _max = -10, 10

# generate 2 2d grids for the x & y bounds
x, y = np.meshgrid(np.linspace(_min, _max, n), np.linspace(_min, _max, n))

# generate z values with random noise
z = np.array([np.zeros(n) for i in range(n)])

for i in range(len(z)):
    z[i] = z[i] + 0.1 * np.random.randint(0, 3, size=len(z[i]))

# plotting
fig, ax = plt.subplots()
c = ax.pcolormesh(x, y, z, cmap='RdBu', vmin=-1, vmax=1)

ax.set_title('pcolormesh')

plt.plot([5, 5, -2.5], [5, -5, 5], color='darkblue', marker='o', markersize=15, linewidth=0)  # dots (outer)
plt.plot([5, 5, -2.5], [5, -5, 5], color='lightblue', marker='o', markersize=10, linewidth=0)  # dots (inner)

plt.grid(b=True)  # background grid

# set the limits of the plot to the limits of the data
ax.axis([_min, _max, _min, _max])
fig.colorbar(c, ax=ax)

x = np.arange(0., 5., 0.2)
plt.plot(x, np.exp(x))

plt.show()

当然,您需要使用所需的y = np.exp(x)任何功能更改线路。


推荐阅读