python - 在 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
:.
有人可以指出我如何实现这一点吗?我尝试了多次,但无法弄清楚... :( 非常感谢提前!!!
注意:早期版本不精确。尽管似乎数据操作是问题,但它错误地将其解释为绘图问题。为此道歉!
解决方案
你只需要绘制一个函数,以同样的方式。
用这些线我在你的情节上绘制一个函数。
# 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)
任何功能更改线路。
推荐阅读
- python - 如何将新值附加到字典中的列表并将其写入 JSON 文件
- javascript - 使用 React.useState 钩子在 2 个状态(数字)之间交替
- autohotkey - 用户帐户窗口不允许任何热键
- javascript - 通过 POST 方法通过 Javascript 提交表单
- java - 插入数据 AndroidStudio/PHP/Java 的问题
- html - Bootstrap Carousel - 将下一个和上一个按钮放在右上角并彼此靠近
- algorithm - 有效计算给定时间范围内的独立事件
- python - 如何获得熊猫 pct_change 的百分比结果?
- flutter - vscode中flutterapp中未验证的断点。我该如何克服这个问题?
- python - C# -> Python 编码和解码网络摄像头流