[英]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.meshgrid
將x1
和x2
為正確的格式:
x1, x2 = np.meshgrid(x1,x2)
然后使用這些2D數組生成z
。
但是,請注意,創建10000x10000曲面可能會占用大量內存!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.