簡體   English   中英

3D曲面圖genfromtxt

[英]3d surface plot genfromtxt

我在通過讀取文本文件來繪制3d表面圖時遇到了問題。 問題是,我使用的是不同的數據類型,例如float,int和string。.我已經將代碼附加了要解析的示例數據。.我希望對代碼進行任何注釋以使其能夠正常工作...

我現在得到的錯誤是ValueError:元組的大小必須匹配字段數。

提前thnx。

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from numpy import genfromtxt
fig = plt.figure(figsize=(12,12))
ax = fig.add_subplot(111, projection='3d') #ax = Axes3D(fig) 
ax.set_title("Plot 3d",fontsize=14)
ax.set_xlabel('Voltage (V)', fontsize=12)
ax.set_ylabel('Pulse Delay(ms)', fontsize=12)
ax.set_zlabel('Pulse Width(ms)', fontsize=12)
ax.grid(True, linestyle='-', color='0.75')
x,y,z,m =genfromtxt('sample.txt', dtype=[('col1', 'f15'), ('col2', 'i15'), ('col3',   'i15'), ('col4', 'S15')],  unpack=True)

use_colours = []
for tmp in m:
    if tmp=='PASS':
        use_colours.append('g')
    else:
        use_colours.append('r')

ax.scatter(x,y,z, s=50, c=use_colours, marker = 'o', linewidths=0);
plt.show()



sample.txt

6.000000    15.000000   21.000000   PASS
6.000000    15.000000   53.000000   PASS
6.000000    15.000000   91.000000   PASS
6.000000    15.000000   104.000000  PASS

在嘗試執行您的代碼時,我發現了一些濫用,如果不知道matplotlib庫的正確功能,就很難避免。

這是一個有效的注釋代碼:

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
fig = plt.figure(figsize=(12, 12))

ax = Axes3D(fig) # ax = fig.add_subplot(111, projection='3d')
ax.set_title("Plot 3d",fontsize=14)
ax.set_xlabel('Voltage (V)', fontsize=12)
ax.set_ylabel('Pulse Delay(ms)', fontsize=12)
ax.set_zlabel('Pulse Width(ms)', fontsize=12)
ax.grid(True, linestyle='-', color='0.75')

# 'i15' and 'f15' are not known as numerical types.
# You can use only 'i8' (np.int64) and 'f16' (np.float128) or 'f8' (np.float64).
# 'f16' seems not to be recognized as a valid type for the scatter library.
# I think that 'f8' and 'i8' are quoit enough.
data = np.genfromtxt('./sample.txt', dtype=[('col1', 'f8'), ('col2', 'i8'), ('col3',   'i8'), ('col4', 'S15')])

# scatter does not take for the c option a list of colours such as ['g', 'g', 'r', ...].
# In this case, we will define data for each colour, not a color for each scatter point.
m = data["col4"]
data1 = data[m == "PASS"]
data2 = data[m != "PASS"]

for dat, color in [(data1, 'g'), (data2, 'r')]:
    # Don't forget that having empty data columns may raise exceptions ...
    try:
        x, y, z = dat['col1'], dat['col2'], dat['col3']
        ax.scatter(xs=x, ys=y, zs=z, s=50, c=color, marker='o', linewidths=0)
    except:
        pass

plt.show()

您得到的錯誤代碼表明您在某些時候傳遞了不適合變量的信息。 這似乎來自genfromtxt調用中的unpack = true標志。 查看有關genfromtxt的一些文檔,似乎使用unpack = True標志將導致“返回的數組已轉置,因此可以使用x,y,z = loadtxt(...)解壓縮參數”,最終導致您的x,y,z和m值看起來像:

x = (6.0, 15, 21, 'PASS') 
y = (6.0, 15, 53, 'PASS') 
z = (6.0, 15, 91, 'PASS')
m = (6.0, 15, 104, 'PASS')

這些值顯然不適用於代碼中的內容。 有趣的是,只有在sample.txt中有4行並試圖解壓縮4個變量時,此方法才有效。

一種解決方案是不標記unpack = true。 相反,這樣的事情應該工作:

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np

## takes a matrix and a column index, returns a list of the values
## in that column
def column(matrix, i):
    return [row[i] for row in matrix]

fig = plt.figure(figsize=(12,12))
ax = fig.add_subplot(111, projection='3d') #ax = Axes3D(fig) 
ax.set_title("Plot 3d",fontsize=14)
ax.set_xlabel('Voltage (V)', fontsize=12)
ax.set_ylabel('Pulse Delay(ms)', fontsize=12)
ax.set_zlabel('Pulse Width(ms)', fontsize=12)
ax.grid(True, linestyle='-', color='0.75')

## Your original call
#x,y,z,m =genfromtxt('sample.txt', delimiter="""", dtype=[('col1', 'f15'),
##('col2','i15'), ('col3',   'i15'), ('col4', 'S15')],  unpack=True)

## The modified call
data = np.genfromtxt('sample.txt', 
                     delimiter='\t', 
                     usecols=(0,1,2,3),
                     dtype=[('col1', 'f15'), 
                           ('col2', 'i15'), 
                           ('col3', 'i15'), 
                           ('col4', 'S15')])

## split the data so that each column in the 2d array ends up in a variable.
## There is a numpy way of doing this, you should look into that
x = column(data, 0)
y = column(data, 1)
z = column(data, 2)
m = column(data, 3)

use_colours = []
for tmp in m:
    if tmp=='PASS':
        use_colours.append('g')
    else:
        use_colours.append('r')

## Let's make sure the values look like we expect:
print x
print "\n"
print y
print "\n"
print z
print "\n"
print m

ax.scatter(x,y,z, s=50, c=use_colours, marker = 'o', linewidths=0);
plt.show()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM