!!! >> I'm a total newbie, I opened matplotlib like 3 hours ago and self-taught myself here. If you introduce any new commands/lines, please let me know what they're called so I can look up tutorials, thanks!
Attempting to: Make a 3d plot of tracks/lines
Problem: I have a .csv files with 29 sets of x y z data points with 49 rows (time points). i.e. I'm tracking 29 particles in 3d space over 49 timepoints. The column headers ATM are "x1, y1, z1, x2, y2, z2 ..." etc. The 3D part is not an issue, but I'm kind of not interested in writing out 70 lines of the same thing.
I.e. I'd rather not write:
x = points['x'].values
x2 = points['x2'].values
x3 = points['x3'].values
...
x29 = points['x29'].values
etc.
Is there a way to say "plot x1,y1,z1 to x29,y29,z29 from that .csv" instead?
from mpl_toolkits.mplot3d import Axes3D
import sys
import matplotlib.pyplot as plt
import pandas
import numpy as np
points = pandas.read_csv('D:Documents\PYTHON_FILES/test3d.csv')
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x = points['x'].values
y = points['y'].values
z = points['z'].values
x2 = points['x2'].values
y2 = points['y2'].values
z2 = points['z2'].values
ax.plot(x, y, z, c='red', marker='o', linewidth=1.0, markersize=2)
ax.plot(x2, y2, z2, c='blue', marker='o', linewidth=1.0, markersize=2)
plt.show()
Thanks in advance!
CodePudding user response:
Yes, based on your code who have things labelled as x
, x2
and so on...
So, the logic is:
- Use a for loop to iterate over numbers
- Use f-strings to make things easier.
Here's the code:
for i in range(1, 30):
if i == 1: i = '' #x is your first value not x1
ax.plot(points[f"x{i}"], points[f"y{i}"], points[f"z{i}"], c='red', marker='o', linewidth=1.0, markersize=2)
F-strings are basically strings but with variables.
You can write f
before a string and use {}
brackets to add variables.
Note, both of them give the same output:
a = "!"
print("Hello" a)
print(f"Hello{a}")
CodePudding user response:
Since it's a fixed number of rows you can iterate over a range to get values. If it weren't fixed, you could count rows and use that to set the range.
for idx in range(29):
suffix = '' if idx == 0 else str(idx 1) # ranges start at 0
x = points[f"x{suffix}"].values
y = points[f"y{suffix}"].values
z = points[f"z{suffix}"].values
ax.plot(x, y, z, c='red', marker='o', linewidth=1.0, markersize=2)
plt.show()
UPDATE: responding to @TheMyth's comments