Matplotlib:在散点图中连接数据点

3

我正在尝试可视化一些关于进程运行或空闲时间的数据。对于每个进程,我有 a_x_axis 表示进程开始运行的时间和 a_live_for 表示它从唤醒后存活的时间。每个进程有两个数据点。我想通过连接第一个绿色点和第一个红色点、第二个绿色点和第二个红色点等方式来用线连接这两个点,以便在大型数据集中查看每个进程的存活和空闲时间。我查看了散点图示例,但找不到解决此问题的方法。

import matplotlib.pyplot as plt

a_x_axis = [32, 30, 40, 50, 60, 78]
a_live = [1, 3, 2, 1, 2, 4]

a_alive_for = [a + b for a, b in zip(a_x_axis, a_live)]

b_x_axis = [22, 25, 45, 55, 60, 72]
b_live = [1, 3, 2, 1, 2, 4]
b_alive_for = [a + b for a, b in zip(b_x_axis, b_live)]

a_y_axis = []
b_y_axis = []

for i in range(0, len(a_x_axis)):
    a_y_axis.append('process-1')
    b_y_axis.append('process-2')


print("size of a: %s" % len(a_x_axis))
print("size of a: %s" % len(a_y_axis))
plt.xlabel('time (s)')
plt.scatter(a_x_axis, [1]*len(a_x_axis))
plt.scatter(a_alive_for, [1]*len(a_x_axis))

plt.scatter(b_x_axis, [2]*len(b_x_axis))
plt.scatter(b_alive_for, [2]*len(b_x_axis))

plt.show()

enter image description here


我想将第一个 a_x_axis 值与第一个 a_alive_for 值相连,第二个值与第二个值相连。在图中,将第一个绿点与第一个红点连接起来,第二个绿点与第二个红点连接起来,以此类推。 - Zeeshan Hayat
@HarvIpan 这段代码没有错误。附图是由该代码生成的。 - Zeeshan Hayat
@ZeeshanHayat,不是这样的。我运行了代码,y轴有你试图散点图的字符串。 - harvpan
它在我的系统上运行正常,无论如何...我已经做出了必要的更改,你现在可以检查一下。 - Zeeshan Hayat
@HarvIpan,请告诉我它是否仍然无法工作。 - Zeeshan Hayat
显示剩余9条评论
2个回答

1
你需要:

import matplotlib.pyplot as plt

a_x_axis = [32, 30, 40, 50, 60, 78]
a_live = [1, 3, 2, 1, 2, 4]

a_alive_for = [a + b for a, b in zip(a_x_axis, a_live)]

b_x_axis = [22, 25, 45, 55, 60, 72]
b_live = [1, 3, 2, 1, 2, 4]
b_alive_for = [a + b for a, b in zip(b_x_axis, b_live)]

a_y_axis = []
b_y_axis = []

for i in range(0, len(a_x_axis)):
    a_y_axis.append('process-1')
    b_y_axis.append('process-2')


print("size of a: %s" % len(a_x_axis))
print("size of a: %s" % len(a_y_axis))
plt.xlabel('time (s)')
plt.scatter(a_x_axis, [1]*len(a_x_axis))
plt.scatter(a_alive_for, [1]*len(a_x_axis))

plt.scatter(b_x_axis, [2]*len(b_x_axis))
plt.scatter(b_alive_for, [2]*len(b_x_axis))

for i in range(0, len(a_x_axis)):
    plt.plot([a_x_axis[i],a_alive_for[i]], [1,1], 'green')

for i in range(0, len(b_x_axis)):
    plt.plot([b_x_axis[i],b_alive_for[i]], [2,2], 'green')

plt.show()

输出:

enter image description here


1
谢谢,这正是我在寻找的。 - Zeeshan Hayat
@ZeeshanHayat 很高兴能帮助你。祝你编程愉快。 - harvpan

0

scatter 不是绘制线条的工具,它是 plot。而且它接受 x 和 y 坐标的 2D 数组,因此您不必手动迭代列表。所以您需要像这样的东西:

plt.plot([a_x_axis, a_alive_for], [[1]*n,[1]*n], 'green')

使用n = len(a_x_axis)

然而,你可以在numpy数组或pandas数据框中更好地组织你的数据,这样你可以为列设置标题。(通过将'process-x'附加到你的数据列表中,你是不是想实现这个目的呢...?)

此外,我觉得你选择标记的颜色似乎没有特别的目的;如果你想让它们与线条的颜色相同,甚至可以完全不使用scatter


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接