2

I have a file with 3000 points in it. I have to plot a 3D scatter plot with those points.the points are as follows,

6.655597594660206395e-01,-5.205175889492101859e-01,4.583497554501108073e-01
3.357418723194116605e-02,-2.482341476533565849e+00,2.009030294705723030e+00
-1.398411818716352728e-01,-1.990250936356241063e+00,2.325394845551588929e+00

there are 3000 such points.

I have the code and it shows the error

TypeError: Cannot cast array data from dtype('float64') to dtype('<U32') according to the rule 'safe'

code I have written

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

x=[]
y=[]
z=[]

with open('3dpd.out') as f:
    lines = f.readlines()
    for line in lines :
        x.append(line.split(',')[0])
        y.append(line.split(',')[1])
        z.append(line.split(',')[2])


fig = plt.figure()
ax = fig.add_subplot(111,projection='3d')

ax.set_title("Scatter Plot")
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')


ax.scatter(x, y, z, c='r')

plt.show()
1
  • 1
    guess that some of your data points are strings and not numbers, can you check data type of all points? Commented Oct 27, 2018 at 12:00

1 Answer 1

1

When lines are read by readlines, they are read in as strings, so you need to convert these strings to numbers.

Also, note that I've separated each step into a different line in the code (eg, split, float, etc) which usually helps in debugging. (And you only need to call split once for each line.)

Here's an example that works:

enter image description here

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

x=[]
y=[]
z=[]

with open('3dpd.out') as f:
    lines = f.readlines()
    for line in lines :
        xs, ys, zs =  line.split(',')
        xv, yv, zv = [float(v) for v in (xs, ys, zs)]
        x.append(xv)
        y.append(yv)
        z.append(zv)

print type(xs)
print type(xv)

fig = plt.figure()
ax = fig.add_subplot(111,projection='3d')

ax.set_title("Scatter Plot")
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')


ax.scatter(x, y, z, c='r')

plt.show()
Sign up to request clarification or add additional context in comments.

Comments

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.