1

Using numpy Packet i produced vectors (arrays) contain x,y,z-coordinates of several atoms in a protein. I would like to plot these vectors.

Does anybody know how to do this? Since I could't plot the array itself, I tried to plot the coordinations of the atoms with a loop as following:

from matplotlib import pyplot as pot
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
for i in range(3):
   plt.plot(atom1[i],atom2[i])

In this case I got the following error message: TypeError: object of type 'float' has no len()

I appreciate any help :)

1 Answer 1

2

The error occurs because plt.plot(x, y) expects x and y to be lists or arrays which have a length while you have given it a float. You could avoid this by enclosing [atom1[i]] in square brackets making it a list.

However, it is usually best to avoid this as it is unclear what is going on. Instead of looping through each atom just stick them all together into one array then plot the columns of the array. You may even find when you create the atoms you can just create them in an array in the first place. Example:

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

# Define several atoms, these are numpy arrays of length 3
# randomly pulled from a uniform distribution between -1 and 1

atom1 = np.random.uniform(-1, 1, 3)
atom2 = np.random.uniform(-1, 1, 3)
atom3 = np.random.uniform(-1, 1, 3)
atom4 = np.random.uniform(-1, 1, 3)

# Define a list of colors to plot atoms

colors = ['r', 'g', 'b', 'k']

# Here all the atoms are stacked into a (4, 3) array
atoms = np.vstack([atom1, atom2, atom3, atom4])

ax = plt.subplot(111, projection='3d')

# Plot scatter of points
ax.scatter3D(atoms[:, 0], atoms[:, 1], atoms[:, 2], c=colors)

plt.show()

I added the colors since it is helpful to see which atom is which.

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

2 Comments

Thank you very much for your detailed answer. It was very helpful, but I need also to know if i can draw vectors between atoms. i.e., I want to plot the vector that goes from atom1 to atom2, for example.
Rather than using scatter just use ax.plot(atoms[:, 0], atoms[:, 1], atoms[:, 2]). This draws a line between each of the points in atoms. You will have to decide how to segment it e.g atoms[0:1, 0] gives the x coordinates of the first two atoms.

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.