首页 > 解决方案 > 使用散点图可视化列表字典中的数据

问题描述

我有一个列表字典:

topic_words_dict = {0: [[-0.669712, 0.6868, 0.9821409999999999, 0.287708],[-0.925967, 0.6138399999999999, 1.247525, 0.740929]],
 1: [[-0.862131, 0.890915, 1.07759, 0.295002],[-0.437658, 0.279271, 0.627497, 0.322339]],
 2: [[-0.671647, 0.670583, 0.937155, 0.334581], [-0.675347, 0.466983, 0.8505440000000001, 0.5795710000000001]],
 3: [[-0.8414590000000001, 0.797826, 1.124295, 0.40925300000000003], [-0.567535, 0.40820300000000004, 0.811368, 0.429982]],
 4: [[-0.8560549999999999, 1.0617020000000001, 1.579302, 0.282398], [-0.576105, 0.5029239999999999, 0.9392, 0.400042]],
 5: [[-0.858527, 0.924175, 1.333083, 0.336538], [-0.562329, 0.37295500000000004, 0.9964350000000001, 0.439751]]
 }

其中键 0 到 5 代表 6 个主题,值代表词的嵌入。根据“topic_words_dict”字典,每个主题都包含两个词的嵌入,例如:

0: [[-0.669712, 0.6868, 0.9821409999999999, 0.287708],[-0.925967, 0.6138399999999999, 1.247525, 0.740929]],

这里的主题“0”包含两个词嵌入 [-0.669712, 0.6868, 0.9821409999999999, 0.287708] 和 [-0.925967, 0.6138399999999999, 1.247525, 0.740929]
在 Python 3.x
中,如何使用散点图将其可视化) 在他们的主题下,其中每个主题将表示为标签。如下所示:

plt.scatter(值,标签=键)
plt.legend()

我没有找到一些我可以轻松理解的清晰文档。请帮忙。感谢您的宝贵时间。

标签: pythonpython-3.xdictionarymatplotlibplot

解决方案


在 Python 3.x 中,当遍历字典时,可以使用items()方法同时检索其键和对应的值。

import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots()

topic_words_dict = {0: [[-0.669712, 0.6868, 0.9821409999999999, 0.287708],[-0.925967, 0.6138399999999999, 1.247525, 0.740929]],
 1: [[-0.862131, 0.890915, 1.07759, 0.295002],[-0.437658, 0.279271, 0.627497, 0.322339]],
 2: [[-0.671647, 0.670583, 0.937155, 0.334581], [-0.675347, 0.466983, 0.8505440000000001, 0.5795710000000001]],
 3: [[-0.8414590000000001, 0.797826, 1.124295, 0.40925300000000003], [-0.567535, 0.40820300000000004, 0.811368, 0.429982]],
 4: [[-0.8560549999999999, 1.0617020000000001, 1.579302, 0.282398], [-0.576105, 0.5029239999999999, 0.9392, 0.400042]],
 5: [[-0.858527, 0.924175, 1.333083, 0.336538], [-0.562329, 0.37295500000000004, 0.9964350000000001, 0.439751]]
 }

for key, value in topic_words_dict.items():
    ax.scatter(value[0],value[1],label=key)
plt.xlabel('x-axis')
plt.ylabel('y-axis')
plt.legend()

在此处输入图像描述


推荐阅读