简体   繁体   中英

How to make matplotlib draw discontinuous line segments?

The test array:

  import numpy as np

  ta = np.array([[[ 1.,  0.],
                  [1.,   1.]],

                 [[ 2.,  1.],
                  [ 2.,  2.]],

                 [[ 5.,  5.],
                  [ 5.,  6.]]])

Each element of ta corresponds to the two endpoints if a line segment. For example:

ta[0] = np.array([[ 1,  0],
                  [1,   1]])

is a line segment with one endpoint at (1,0) and another at (1,1) .

How can I make matplotlib plot out these line segments, while keeping them discontinuous ?

The following didn't work:

from matplotlib import pyplot as plt

ta_xs = ta[:,:,0]
ta_ys = ta[:,:,1]

plt.plot(np.insert(ta_xs, np.arange(0, len(ta_xs)), np.nan), np.insert(ta_ys, np.arange(0, len(ta_ys)), np.nan))

The above attempted solution was inspired by the answer to this question: How to drop connecting lines where the function is discontinuous

Inserting NaN's is a perfectly fine way to do this, but if you're wanting to plot multiple vertical line segments, it's easier to use plt.vlines .

For example:

import matplotlib.pyplot as plt

x = [1, 2, 5]
ymin = [0, 1, 5]
ymax = [1, 2, 6]

plt.margins(0.05) # So the lines aren't at the plot boundaries..
plt.vlines(x, ymin, ymax, color='black', linewidth=2)
plt.show()

在此处输入图片说明

Alternatively, if your data is already in an array form similar to your example, just do something like:

import numpy as np
import matplotlib.pyplot as plt

ta = np.array([[[ 1.,  0.],
              [1.,   1.]],
             [[ 2.,  1.],
              [ 2.,  2.]],
             [[ 5.,  5.],
              [ 5.,  6.]]])
x, y = ta.T

plt.margins(0.05)
plt.plot(x, y, linewidth=2, color='black')
plt.show()

在此处输入图片说明

plot will interpret 2D arrays passed in as x and y to be separate lines.

You are on the right track, but be sure you have a floating-point array, otherwise you can't insert nan. I get an exception: ValueError: cannot convert float NaN to integer . Try:

np.insert(ta_xs.astype(float), np.arange(1, len(ta_xs)), np.nan)

Scratch that. Try this:

tas_for_plotting = np.concatenate([ta, nan*np.ones_like(ta[:,:1])], axis=1)
plot(tas_for_plotting[...,0].flat, tas_for_plotting[...,1].flat)

plt.plot(np.insert(ta_xs, np.arange(2, len(ta_xs), 2), np.nan), np.insert(ta_ys, np.arange(2, len(ta_ys), 2), np.nan))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM