4

I have the following code to try to create a 3d Plot for a dataset YearlyKeywordsFrequency. I cannot figure out why is this error coming

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()

This code gives the following Results with error

              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

I am trying to make a chart something like this Same Dataset 3d plot in Excel but i cant understand why is it giving an error when a 2d array is required and my array shape is (8374,4) so what is the problem.

2 Answers 2

4

You must change your x and y types to arrays:

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()

This gives: enter image description here

Obviously you must change colors and x and y accordingly to get your desired output.

Sign up to request clarification or add additional context in comments.

Comments

3

x, y, and data are not compatible.

type(data) gives <class 'numpy.ndarray'>

type(x) gives <class 'range'>

type(y) gives <class 'range'>

On the other hand, in this example, all of X, Y, and Z are of <class 'numpy.ndarray'> type. I think that you should try converting x and y to arrays.

5 Comments

still the same error after type of data,x,y is <class 'numpy.ndarray'> <class 'numpy.ndarray'> <class 'numpy.ndarray'>
Are x, y and data all of the same shape?
what i feel is that when i print data there is no comma between values so if there was a way to put comma in them... maybe it might work.
asymmetryFan they are of required shape as you can see in the code.
@HaseebHassanAsif If you do print(repr(data)) instead of print(data), there should be commas, but it's just a representation thing, nothing more.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.