本文介绍了为什么 Z 必须是二维的才能在 matplotlib 中进行 3d 绘图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 使用 matplotlib:

I am trying to plot 3d Surface plots using code from this site using matplotlib:

X、Y 和 Z 得到如下:

X,Y and Z are obtained as below:

from math import pi
from numpy import cos, meshgrid
alpha = 0.7
phi_ext = 2 * pi * 0.5

def flux_qubit_potential(phi_m, phi_p):
    return 2 + alpha - 2 * cos(phi_p)*cos(phi_m) - alpha * cos(phi_ext - 2*phi_p)

phi_m = linspace(0, 2*pi, 100)
phi_p = linspace(0, 2*pi, 100)
X,Y = meshgrid(phi_p, phi_m)
Z = flux_qubit_potential(X, Y).T

使用以下代码完成 3d 绘图:

And 3d plotting is done with following code:

from mpl_toolkits.mplot3d.axes3d import Axes3D

fig = plt.figure(figsize=(14,6))

# `ax` is a 3D-aware axis instance, because of the projection='3d' keyword argument to add_subplot
ax = fig.add_subplot(1, 2, 1, projection='3d')

p = ax.plot_surface(X, Y, Z, rstride=4, cstride=4, linewidth=0)

# surface_plot with color grading and color bar
ax = fig.add_subplot(1, 2, 2, projection='3d')
p = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm, linewidth=0, antialiased=False)
cb = fig.colorbar(p, shrink=0.5)

但是,如果我用我的 x、y、z 3d 数据(示例如下)替换 X、Y 和 Z,则会出现 Z 必须是二维的错误.如何使用通常的 x、y、z 值进行绘图,如下所示:

However, if I replace X,Y and Z by my x,y,z 3d data (sample give below), there is an error that Z has to be 2 dimensional. How can I plot with usual x,y,z values, as following:

   x   y   z
0  12  0  0.1
1  13  1  0.8
2  14  3  1.0
3  16  4  1.2
4  18  4  0.7

推荐答案

这是因为,在我看来,要绘制一个表面,您需要形成一个 多边形网格.要绘制 3d 表面,您需要有小方块,例如,在 xy 平面上,然后所有 x-y 点都有 1 个对应的 z 值.正方形的面积越小意味着更精细的网格和更好的分辨率(光滑的表面).现在如果你有一组任意的 xyz 点,matplotlib 如何确定要绘制的表面.这就是为什么需要网格的原因.您当然可以绘制 3d scatter线图 与您的数据.

This is because, in my understanding, to draw a surface you need to form a polygon mesh. To draw a 3d surface, you need to have small squares, for example, on the xy-plane and then have 1 corresponding z value for all the x-y points. The smaller the area of the square means finer mesh-grid and better resolution(smooth-looking surface.) Now if you have an arbitrary set of xyz points, how matplotlib can determine which surface to draw. That is why a mesh is required. You can of course plot 3d scatter or line plots with your data.

这篇关于为什么 Z 必须是二维的才能在 matplotlib 中进行 3d 绘图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 17:39