通过在Python中创建一个列表,我需要(使用Matplotlib和Python)使用Y轴上的一个步骤在另一个列表下绘制它们。
例如:ll = [[1,2,3], [0,3,4]]
对于列表列表ll
,Y轴上的步长将是4(最大值)。将偏移量初始化为0。随着每个列表的绘制,偏移量将随着Y轴上的步长而增加。X轴上的值对于每个列表都是1,2,3
,因为每个子列表中都有3个点。
Y轴上的值对于第一个列表是1,2,3
(偏移量是0),对于第二个列表是4,6,7
,我已经为每个元素添加了偏移量(0+step( 4) =4)。
对于下一个元素,偏移量将是8。这个值将被添加到第三个列表中的每个元素(如果它存在于示例中),依此类推……此外,我需要从相同的列表中的点被连接。ll
可以包含2个以上的列表。该图将如下所示:
我写的代码如下:
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()
我得到的结果是:
怎样才能得到想要的结果呢?我应该在我的代码中修改什么?
发布于 2018-12-07 06:54:39
我相当肯定你让这件事比它应该做的更复杂了。
这里有一段代码可以完成你想要的(我添加了一条水平的灰色虚线来显示下一个“列表”的开始位置)
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()
发布于 2018-12-07 07:52:26
我的方法是在一个plot命令中绘制所有的线,包括圆。
因此,我使用ll
的numpy数组表示,并从第二个开始将偏移量添加到所有子列表。偏移量的数组就是每个子列表的最大值的累积和。
import numpy as np
import matplotlib.pyplot as plt
ll = [[1,2,3], [1,3,4], [2, 3, 4], [1, 1, 2]]
arr = np.array(ll).T
arr[:, 1:] += np.cumsum(np.max(arr[:, :-1], axis=0))
plt.subplots()
plt.plot([1, 2, 3], arr, '-o', mfc='w')
https://stackoverflow.com/questions/53659725
复制相似问题