现在我正在使用这样的列表进行绘图:
eje_x1 = (0,6,10)
eje_y1 = (1,1,0)
label1 = 'Label1'
eje_x2 = (8,12,15,19)
eje_y2 = (0,1,1,0)
label2 = 'Label2'
eje_x = (eje_x1, eje_x2)
eje_y = (eje_y1, eje_y2)
labels = (label1, label2)
for x,y,label in zip(eje_x, eje_y, labels):
plt.plot(x, y, label=label)
plt.legend(loc='best')
plt.show()
但我想使用字典来清理我的代码,如下所示。
myDict = {
'Label1': ((0,1),(6,1),(10,0)),
'Label2': ((8,0),(12,1),(15,1),(19,0))
}
我可以“直接”绘制这个dict
吗?我读过一些帖子,其中一个轴是关键,但不是这种结构。
非常感谢!
最佳答案
迭代字典并重新排列其中的点:
for label, points in myDict.items():
plt.plot(*zip(*points), label=label)
plt.legend(loc="best")
plt.show()
其中 zip(*...)
有点转置点,使 xs 在一起,ys 在一起。另一个 *
将它们解压到 plt.plot
用作第一个和第二个参数,恰好是 xs 和 ys,
获取
在 zip(*...)
上:
>>> points
((8, 0), (12, 1), (15, 1), (19, 0))
>>> list(zip(*points))
[(8, 12, 15, 19), (0, 1, 1, 0)]
关于python - 是否可以使用字典中的数据绘制线条?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68015669/