python - 如何在Y轴不同高度上绘制列表列表?

标签 python list matplotlib

通过使用 Python 中的列表列表,我需要使用 Y 轴上的步骤将它们绘制在另一个列表下(使用 Matplotlib 和 Python)。
例如:ll = [[1,2,3], [0,3,4]]

对于 ll(列表的列表),Y 轴上的步长将为 4(最大值)。 偏移量初始化为 0。 对于绘制的每个列表,偏移量将随着 Y 轴上的步长而增加。 对于每个列表,X 轴上的值将为 1,2,3,因为每个子列表中有 3 个点。
第一个列表的 Y 轴值是 1,2,3(偏移量为 0),第二个列表的 Y 轴值是 4,6,7,我有为每个元素添加了偏移量(0+step(4) = 4)。

对于下一个元素,偏移量将为 8。该值将添加到第三个列表中的每个元素(如果它存在于示例中),依此类推... 我还需要连接同一列表中的点。 ll 可以包含不止 2 个列表。 情节如下:
Plotted list of lists

我写的代码:

x = np.arange(0, len(list_of_lists[0]))
y = list_of_lists[0]

step_on_y = max([item for sublist in list_of_lists for item in sublist])

lines = []
rows = 0
for list_in in range(len(list_of_lists)):
    for i in range(0, len(list_of_lists[list_in]) - 1):
        pair = [(x[i], list_of_lists[list_in][i] + rows), (x[i + 1], list_of_lists[list_in][i+1] + rows)]
        lines.append(pair)
    rows = rows + step_on_y

linecoll = matcoll.LineCollection(lines)
fig, ax = plt.subplots()

ax.add_collection(linecoll)
print(len(x), len(list_of_lists)*len(list_of_lists[0]))
plt.scatter(x, y, s=1)

plt.xlabel('X')
plt.ylabel('Y')
plt.xticks(x)
plt.ylim(0, 30)

plt.show()

我得到的结果: The result I get

怎样才能得到想要的结果?我应该修改我的代码中的哪些内容?

最佳答案

我相当肯定你让这件事变得比应有的更加复杂。

这是一段代码,应该可以满足您的要求 (我添加了一条水平灰色虚线来显示下一个“列表”的绘图的开始位置)
PS:在这个例子中,我使用前一个列表的最大值作为下一个列表的偏移量,以确保图之间没有重叠,但您可以轻松地使其恒定或自定义它

import numpy as np
import matplotlib.pyplot as plt

ll = [[1,2,3], [1,3,4], [1,1,1], [4,5,6]]
c = ['k','r','b','g','c']

x = np.arange(0, len(ll[0]))
a = np.array( ll)


step = 0
ax = plt.subplot()
for n,l in enumerate( a):
    ax.plot(x, l + step)
    ax.scatter(x, l + step)
    ax.axhline(y=step, color='#cccccc', dashes=[5,3])

    step += np.max(l)

plt.show()

关于python - 如何在Y轴不同高度上绘制列表列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53659725/

相关文章:

python - uWSGI + 构建 Go .so 不工作

python - 带有名称和输入的 If 语句

Python:通过匹配特定元素将列表的子集转换为字典

java - 在列表的时间范围内查找元素的快速算法

python - 如何增加 matplotlib 条形图中错误线的粗细?

python - 如何允许用户使用 Django 编辑帖子?

python - 如果使用嗅探器重新执行, Pyramid 应用程序的测试将失败

python - 将作为列表的字符串转换为适当的列表 python

Python:在一张图中绘制所有分类子集组合

python - 如何在误差线旁边添加误差值?