1

What is the possible way to connect dots I needed?

Here is part of my code for you to understand what I mean:

x = [0, 5, 10, 15, 100, 105, 110, 115]
y = [15, 10, 5, 0, 115, 110, 105, 100]
plt.figure(figsize=(5, 5))

plt.xlim(-1, 120)
plt.ylim(-1, 120)
plt.grid()      

plt.plot(x, y, 'og-')

Have this:

Connected points

But I have to connect those grouped dots from (0, 15) to (15, 0) and (100, 115) to (115, 100) only. I do not need that long connection between the dots: (15, 0) to (100, 115)

Illustration of the connection

Can anyone help find a solution for this problem?

2
  • 2
    It's not a mind reader. When you give it a series of points, there is no way for it to determine one segment should not be drawn. Separating the segments is YOUR job. Commented Oct 8, 2021 at 16:39
  • Oh, you want to drop lines segments that exceed a certain length. I think there's an answer now. Commented Oct 8, 2021 at 20:19

2 Answers 2

2

If you have a very long x-array, you can combine numpy's np.diff with np.nonzero to calculate the indices. np.diff would calculate the subsequent differences, which can be compared to a threshold. np.nonzero will return all indices where the comparison results in True. Looping through these indices lets you draw each part separately.

from matplotlib import pyplot as plt
import numpy as np

x = [0, 5, 10, 15, 100, 105, 110, 115]
y = [15, 10, 5, 0, 115, 110, 105, 100]
threshold = 20
indices = np.nonzero(np.diff(x) >= threshold)[0] + 1

for i0, i1 in zip(np.append(0, indices), np.append(indices, len(x))):
    plt.plot(x[i0:i1], y[i0:i1], '-go')
plt.show()

Here is a more elaborate example:

from matplotlib import pyplot as plt
import numpy as np

N = 30
x = (np.random.randint(1, 5, N) * 5).cumsum()
y = np.random.randint(0, 10, N) * 5
plt.plot(x, y, 'r--') # this is how the complete line would look like
threshold = 20
indices = np.nonzero(np.diff(x) >= threshold)[0] + 1
for i0, i1 in zip(np.append(0, indices), np.append(indices, len(x))):
    plt.plot(x[i0:i1], y[i0:i1], '-go')
plt.show()

drawing a line in pieces

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

1 Comment

Thank you, will think about it.
1

draw the lines you want, and don't draw the ones you don't:

from matplotlib import pyplot as plt
#x = [0, 5, 10, 15, 100, 105, 110, 115]
#y = [15, 10, 5, 0, 115, 110, 105, 100]

plt.figure(figsize=(5, 5))

plt.xlim(-1, 120)
plt.ylim(-1, 120)
plt.grid()   

x1 = [0, 5, 10, 15]
y1 = [15, 10, 5, 0]

x2 = [100, 105, 110, 115]
y2 = [115, 110, 105, 100]


plt.plot(x1, y1, 'og-')
plt.plot(x2,y2, 'og-')

plt.show()

Output:

1 Comment

Imagine you have a very big array.

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.