user388794
user388794

Reputation: 33

Matplotlib in python | connecting dots

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?

Upvotes: 1

Views: 1876

Answers (2)

JohanC
JohanC

Reputation: 80329

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

Upvotes: 2

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:

Upvotes: 1

Related Questions