python - 是否可以使用字典中的数据绘制线条?

标签 python matplotlib

现在我正在使用这样的列表进行绘图:

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()

enter image description here

但我想使用字典来清理我的代码,如下所示。

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,

获取

enter image description here


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/

相关文章:

python - 无法为 Python 3 安装 Python 虚拟环境

python - 使用交互式小部件运行 Bokeh

python - 在 python 中将 pcolormesh 与 3 个一维数组一起使用

python - 仅调整 matplotlib 中两个子图之间的距离

python - 在 python/pyplot 中绘制任意二维函数,如 Matlab 的 Ezplot

python - 有没有一种简单的方法可以在 Python 正则表达式中使用和忽略元字符之间进行切换?

python - Flask 在 POST 上忘记路由

Python:将数据输出到 Excel 电子表格

python - 查找两个 numpy 数组的交点坐标

python - rpy + matplotlib + arcpy