matplotlib传入奇数条线段时Axes.plot绘制出多余线条问题
问题成因
matplotlib.axes.Axes.plot绘制多条线段时,要求输入参数为每组线段独立的x坐标序列, y坐标序列对。直接对多层嵌套的line_list整体解包传入的方式,仅在2条线段时凑巧匹配参数结构,当线段数量大于等于3时就会出现维度不匹配,导致绘制逻辑异常,出现线段错位、多余线段的问题。
解决方案
推荐使用逻辑最清晰、兼容性最好的循环绘制方式,修改后的完整代码如下:
points = [[0, 1], [1, 2], [1, 3], [2, 4], [0, 2.5], [0.5, 3.5]] line_list = [[[0, 1], [1, 2]], [[1, 3], [2, 4]], [[0, 2.5], [0.5, 3.5]]] import matplotlib.pyplot as plt fig = plt.figure() ax = plt.axes() scatter = ax.scatter(*list(zip(*points))) # 遍历每条线段单独绘制 for seg in line_list: x, y = zip(*seg) ax.plot(x, y) plt.show()
如果不想使用循环,也可以先将line_list预处理为plot方法可识别的平铺参数序列,再一次性传入:
plot_params = [] for seg in line_list: plot_params.extend(zip(*seg)) lines = ax.plot(*plot_params)
内容的提问来源于stack exchange,提问作者Peter
相关产品推荐
相关产品推荐

