我有以下代码尝试为数据集 YearlyKeywordsFrequency 创建 3d Plot。我无法弄清楚为什么会出现此错误

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from mpl_toolkits import mplot3d
myData = pd.read_csv('counted-JOSAIC.csv', delimiter=',', skiprows=0,usecols=range(0,5))
print(myData)
item_list = list(myData.columns)            #Names of Columns
item_list = item_list[1:]
print(item_list)
myData = np.array(myData)                   #Convert to numpy
keywords = np.asarray(myData[:,0])          #Get the Keywords
print(keywords)
data = np.asarray(myData[:,1:])           #remove Keywords from data
print(data.shape)
print(data)
##################################################################################
###x=keyword
###y=year
###z=freq
y=range(len(keywords))
x=range(len(item_list))
fig = plt.figure()
ax = plt.axes(projection='3d')
ax.contour3D(x, y, data, 50, cmap='binary')
ax.set_yticklabels(keywords)
ax.set_xticklabels(item_list)
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z');
plt.show()

此代码给出了以下错误结果
              Kewords   freq-2015     ...       freq-2017   freq-2018
0              energy         526     ...              89          97
1               power         246     ...             170         125
2            wireless         194     ...             121         144
3        transmission         157     ...              77         106
4             optimal         153     ...             100         110
5        interference         136     ...             100          78
6            spectrum         132     ...             126          29
7          allocation         125     ...             143         101
8          harvesting         123     ...               5          11
9                node         114     ...              25          63
10           capacity         106     ...              92          67
11           cellular         102     ...              72          39
12              relay          98     ...              20          35
13             access          97     ...             138          98
14            control          94     ...              50          87
15               link          91     ...              62         105
16              radio          91     ...              78          55
17       localization          89     ...              11           3
18           receiver          84     ...              20          38
19             sensor          82     ...               4          21
20            optical          80     ...               6          50
21         simulation          79     ...              90          94
22        probability          79     ...              51          44
23                the          78     ...              59          64
24               mimo          78     ...             192          49
25             signal          76     ...              38          38
26            sensing          76     ...              33           0
27         throughput          73     ...              65          39
28             packet          73     ...               8          38
29      heterogeneous          71     ...              36          42
          ...         ...     ...             ...         ...
8348            rated           0     ...               0           1
8349              150           0     ...               0           1
8350   highdefinition           0     ...               0           1
8351      facilitated           0     ...               0           1
8352              750           0     ...               0           1
8353              240           0     ...               0           1
8354         supplied           0     ...               0           1
8355          robotic           0     ...               0           1
8356      confinement           0     ...               0           1
8357              jam           0     ...               0           1
8358              8x6           0     ...               0           1
8359        megahertz           0     ...               0           1
8360        rotations           0     ...               0           1
8361           sudden           0     ...               0           1
8362            fades           0     ...               0           1
8363           marine           0     ...               0           1
8364          habitat           0     ...               0           1
8365           probes           0     ...               0           1
8366            uowcs           0     ...               0           1
8367             uowc           0     ...               0           1
8368  manchestercoded           0     ...               0           1
8369        avalanche           0     ...               0           1
8370              apd           0     ...               0           1
8371              pin           0     ...               0           1
8372          shallow           0     ...               0           1
8373           harbor           0     ...               0           1
8374           waters           0     ...               0           1
8375            focal           0     ...               0           1
8376              lcd           0     ...               0           1
8377          display           0     ...               0           1

[8378 rows x 5 columns]
[' freq-2015', ' freq-2016', ' freq-2017', ' freq-2018']
['energy' 'power' 'wireless' ... 'focal' 'lcd' 'display']
(8378, 4)
[[526 747 89 97]
 [246 457 170 125]
 [194 248 121 144]
 ...
 [0 0 0 1]
 [0 0 0 1]
 [0 0 0 1]]
Traceback (most recent call last):

  File "<ipython-input-5-7d351bf710cc>", line 1, in <module>
    runfile('C:/Users/Haseeb/Desktop/Report 5/PYTHON word removal/PlotingCharts.py', wdir='C:/Users/Haseeb/Desktop/Report 5/PYTHON word removal')

  File "e:\ProgramData\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 668, in runfile
execfile(filename, namespace)

  File "e:\ProgramData\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 108, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)

  File "C:/Users/Haseeb/Desktop/Report 5/PYTHON word removal/PlotingCharts.py", line 111, in <module>
ax.contour3D(x, y, data, 50, cmap='binary')

  File "e:\ProgramData\Anaconda3\lib\site-packages\mpl_toolkits\mplot3d\axes3d.py", line 2076, in contour
self.auto_scale_xyz(X, Y, Z, had_data)

  File "e:\ProgramData\Anaconda3\lib\site-packages\mpl_toolkits\mplot3d\axes3d.py", line 494, in auto_scale_xyz
self.xy_dataLim.update_from_data_xy(np.array([x, y]).T, not had_data)

  File "e:\ProgramData\Anaconda3\lib\site-packages\matplotlib\transforms.py", line 913, in update_from_data_xy
path = Path(xy)

  File "e:\ProgramData\Anaconda3\lib\site-packages\matplotlib\path.py", line 127, in __init__
vertices = _to_unmasked_float_array(vertices)

  File "e:\ProgramData\Anaconda3\lib\site-packages\matplotlib\cbook\__init__.py", line 1365, in _to_unmasked_float_array
return np.asarray(x, float)

  File "e:\ProgramData\Anaconda3\lib\site-packages\numpy\core\numeric.py", line 492, in asarray
return array(a, dtype, copy=False, order=order)

ValueError: setting an array element with a sequence

我正在尝试制作类似 python - Matplot Numpy ValueError : setting an array element with a sequence-LMLPHP 的图表,但我无法理解为什么在需要二维数组且我的数组形状为 (8374,4) 时会出现错误,那么问题是什么。

最佳答案

您必须将 xy 类型更改为数组:

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from mpl_toolkits import mplot3d
myData = pd.read_csv('counted-JOSAIC.csv', delimiter=',', skiprows=0,usecols=range(0,5))

item_list = list(myData.columns)            #Names of Columns
item_list = item_list[1:]
print(item_list)
myData = np.array(myData)                   #Convert to numpy
keywords = np.asarray(myData[:,0])          #Get the Keywords
print(keywords)
data = np.asarray(myData[:,1:])           #remove Keywords from data
print(data.shape)
print(data)
##################################################################################
###x=keyword
###y=year
###z=freq
y=np.arange(len(keywords))
x=np.arange(len(item_list))
X, Y = np.meshgrid(x, y)

fig = plt.figure()
ax = plt.axes(projection='3d')
ax.contour3D(X, Y, data, 50, cmap='binary')
ax.set_yticklabels(keywords)
ax.set_xticklabels(item_list)
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z');
plt.show()
这给出:
python - Matplot Numpy ValueError : setting an array element with a sequence-LMLPHP
显然,您必须相应地更改颜色以及 x 和 y 才能获得所需的输出。

关于python - Matplot Numpy ValueError : setting an array element with a sequence,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59136020/

10-12 22:25