繁体   English   中英

如何将一维数组转换为二维数组以使plot_surf()函数在python3中正常工作?

[英]How to convert 1D arrays into 2D arrays for the plot_surf() function to work correctly in python3?

以以下格式编写的原始代码正在运行,没有任何错误,但仍未生成所需的二维功能绘图/曲面。 实际上,我得到的是带有所有标题和标签的3d空间,但没有实际的2d图。 我试图在每个步骤中通过print()函数检查输出。 似乎代码正确生成了z数组,但是surf()没有相应地响应。 因此,问题应该是“代码中缺少什么方法,以便Surface()无法相应地响应?”。

import sys


import matplotlib
matplotlib.use('SVG')
import matplotlib.pyplot as pyplot
from matplotlib.ticker import MaxNLocator
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D

import numpy as np

from numpy import array as ar


import random
from scipy import linspace, meshgrid, arange, empty, concatenate, newaxis, shape

import math

fig =pyplot.figure()
ax = fig.gca(projection='3d')

N = 10000
data1 = [random.random() for i in range(N)]
x1 = ar(data1)
data2 = [random.random() for i in range(N)]
x2 = ar(data2)


a = 2.000000
y1 = np.sqrt((-1.000000) * a * np.log(x1)) * np.cos(2 * math.pi * x2)
y2 = np.sqrt((-1.000000) * a * np.log(x1)) * np.sin(2 * math.pi * x2)
gaussian1 = math.pow(2 * math.pi, (-1.000000 / a)) * np.exp((-1.000000 / a) * y1**a)
gaussian2 = math.pow(2 * math.pi, (-1.000000 / a)) * np.exp((-1.000000 / a) * y2**a)
z = gaussian1 * gaussian2

    surf = ax.plot_surface(x1, x2, z, rstride=1, cstride=1, cmap=cm.jet, linewidth=1.0)
fig.colorbar(surf)

title = ax.set_title("Probability Distribution Function")
title.set_y(1.01)

ax.xaxis.set_major_locator(MaxNLocator(10))
ax.yaxis.set_major_locator(MaxNLocator(10))
ax.zaxis.set_major_locator(MaxNLocator(10))

fig.set_tight_layout(True)
fig.savefig('Gaussian.svg')

问题出在您的阵列中。 从文档到plot_surface

Axes3D.plot_surface(X,Y,Z,* args,** kwargs)

X,Y,Z:数据值作为2D数组

您的X, Y, Z是一维数组,因此无法正常工作。

您可以使用np.meshgridx1x2为正确的格式:

x1, x2 = np.meshgrid(x1,x2)

然后使用这些2D数组生成z

但是,请注意,创建10000x10000曲面可能会占用大量内存!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM