Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/282.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使matplotlib绘制不连续的线段?_Python_Matplotlib - Fatal编程技术网

Python 如何使matplotlib绘制不连续的线段?

Python 如何使matplotlib绘制不连续的线段?,python,matplotlib,Python,Matplotlib,测试阵列: import numpy as np ta = np.array([[[ 1., 0.], [1., 1.]], [[ 2., 1.], [ 2., 2.]], [[ 5., 5.], [ 5., 6.]]]) ta的每个元素对应于线段的两个端点。例如: ta[0] = np.ar

测试阵列:

  import numpy as np

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

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

                 [[ 5.,  5.],
                  [ 5.,  6.]]])
ta
的每个元素对应于线段的两个端点。例如:

ta[0] = np.array([[ 1,  0],
                  [1,   1]])
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()
是一条线段,一个端点位于
(1,0)
,另一个端点位于
(1,1)

如何使
matplotlib
绘制出这些线段,同时保持它们的不连续性

以下操作不起作用:

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))

以上尝试的解决方案的灵感来自于对这个问题的回答:

您的思路是正确的,但请确保您有一个浮点数组,否则无法插入nan。我得到一个异常:
ValueError:无法将浮点NaN转换为整数
。尝试:

np.insert(ta_xs.astype(float), np.arange(1, len(ta_xs)), np.nan)
把它擦掉。试试这个:

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))
插入nan是一种非常好的方法,但是如果您想绘制多条垂直线段,使用
plt.vline
会更容易

例如:

ta[0] = np.array([[ 1,  0],
                  [1,   1]])
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()

或者,如果数据已经以类似于示例的数组形式存在,只需执行以下操作:

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
将把作为x和y传入的二维数组解释为单独的行。

对不起,本,我没有更新我的代码。我的意思是,即使它是浮点数组,也不起作用。试试看。提供的测试代码现在也提供了浮点数组。