1

This is a trivial problem but I run into it again and again and I am sure there is a elegant solution, which I would like to use.

I do math with numpy and would like to plot lines that are results of linear algebra calculations. These lines come in the form enter image description here

So I would would like to "outsource" the job of finding the start end endpoint of my line to a clever sipplet of python code, so that my resulting line gets drawn into my 3D plot, honoring the existing dimensions of the plot. E.g. if I plotted a 3D parabel from x = -2 to 2 and z = -3 to 3, and I wanted to draw a line enter image description here, it would figure out that it would need to start at (-2,1,-2) and end at (2,1,2).

How could that work?

1 Answer 1

3

At first, it's important to define projection parameter. At second, you need to work with different shapes of P, v and z in order to obtain X, Y, Z parameters that corresponds to coordinates of plot method:

import matplotlib.pyplot as plt
import numpy as np

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

P = np.array([1,1,1]).reshape(-1,1)
v = np.array([1,0,1]).reshape(-1,1)
z = np.linspace(-3,3,100)
X, Y, Z = P + v*z

ax.plot(X, Y, Z)
plt.show()

Per comments

reshape(-1, 1) adds an extra dimension which is required for broadcasting (you can also read a nice tutorial on this topic). It is also a substitute of reshape(3, 1). Simple case (arr1 = v; arr2 = np.linspace(-3,3,11)) can be visualized like so:

enter image description here

Ending points of a curve g = (1, 1, 1) + z * (1, 0, 1) are at the bounds of interval of z, namely:

g1 = (1, 1, 1) + (-3) * (1, 0, 1) = (-2, 1, -2)
g2 = (1, 1, 1) + 3 * (1, 0, 1) = (4, 1, 4)

Note that z = 1 is needed to get ending point = (2,1,2)

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

2 Comments

can you please explain what the reshape(-1,1) does? And what about the -3,3 range? That is obviously manual (which is not a major issue). But that is just a rough guess of the range we might be in, right?
@AndreasSchuldei Look at my update.In general, you can solve some equations to find a range required like in my example. One more to mention, np.linspace(-3,3,2) is enough because we need only two points to define a segment.

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.