如何使matplotlib绘制不连续的线段?
这是一个测试数组:
import numpy as np
ta = np.array([[[ 1., 0.],
[1., 1.]],
[[ 2., 1.],
[ 2., 2.]],
[[ 5., 5.],
[ 5., 6.]]])
数组中的每个元素代表一条线段的两个端点。比如:
ta[0] = np.array([[ 1, 0],
[1, 1]])
这是一条线段,一个端点在 (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))
上面的尝试是受到这个问题的启发: 如何去掉函数不连续时的连接线
3 个回答
0
你走在正确的道路上,但要确保你使用的是浮点数组,不然就不能插入nan(不是一个数字)。我遇到了一个错误:ValueError: cannot convert float NaN to integer
。试试这个:
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)
0
这段代码的意思是:使用`plt.plot`这个函数来画图。它的作用是把两个数据集合(`ta_xs`和`ta_ys`)中的某些位置插入一个空值(`np.nan`),然后再把处理过的数据用来绘制图形。
具体来说,`np.insert`这个函数会在`ta_xs`和`ta_ys`的每隔一个位置(从第二个开始)插入一个空值。这样做的目的是为了在图上留出间隔,让数据点之间有空隙,看起来更清晰。
2
插入NaN(不是一个数字)是个不错的方法,但如果你想画多个竖线段,使用 plt.vlines
会更简单。
比如说:
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
会把传入的二维数组当作不同的线来处理。