2

Excuse me little knowledge in python but im trying to output a csv file(csvfile) dataset in a 3d graph. my code so far is as follows:

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import csv
   fig = plt.figure()
   ax = fig.add_subplot(111, projection='3d')

with open('new3.csv') as csvfile:
readCSV = csv.reader(csvfile, delimiter=',')
next(readCSV)
next(readCSV)
next(readCSV)
XS =[]
YS =[]
ZS =[]
for column in readCSV:
    xs = column[1]
    ys = column[2]
    zs = column[3]

    XS.append(xs)
    YS.append(ys)
    ZS.append(zs)
    ax.scatter(XS, YS, ZS, c='r', marker='o')
    ax.set_xlabel('X Label')
    ax.set_ylabel('Y Label')
    ax.set_zlabel('Z Label')

    plt.show()

But i keep coming up with the error in the Title. Any help is appreciated

2 Answers 2

1

The error is because you are trying to plot three lists of str type objects. They need to be of float or similar type, and cannot be implicitly casted. You can do the type casting explicitly by making the modification below:

for column in readCSV:
        xs = float(column[1])
        ys = float(column[2])
        zs = float(column[3])

Also note that ax.scatter should be outside the loop, like this

    for column in readCSV:
        xs = float(column[1])
        ys = float(column[2])
        zs = float(column[3])

        XS.append(xs)
        YS.append(ys)
        ZS.append(zs)

ax.scatter(XS, YS, ZS, c='r', marker='o')
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')

Otherwise you will end up with a new scatter plot for every row in the .csv. I isolated the first 5 rows of your data and plotted them with these modifications to give

3D Scatterplot

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

1 Comment

Thank you very much, this helped me output the full file.
0

just for fun, using numpy which by default circumvents your original issue with passing strings to matplotlib, and at the same time compacting the code a bit.

raw = """
id,gx,gy,gz,ax,ay,az
0,4.47,-33.23,-77,-106,94
1,-129.04,4.48,-33.22,-78,-94,117
2,-129.04,4.49,33.2,-70,-81,138
3,-129.02,4.49,-33.18,-70,-64,157
4,-129.02,4.5,-33.15,-64,-47,165
"""

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from io import StringIO

# read data
csvfile = StringIO(raw)
d = plt.np.loadtxt(csvfile, delimiter=',', skiprows=2, usecols=[1,2,3])
# instead of csvfile just use filename when using the real file
xyz = plt.np.split(d.T, indices_or_sections=len(d.T))

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(*xyz, c='r', marker='o')
ax.set(**{'%slabel'%s: s.upper() + ' Label' for s in 'xyz'})

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.