Python 从字典中的值绘制图表

标签 python list dictionary plot

我有一本看起来像这样的字典:

test = {1092268: [81, 90], 524292: [80, 80], 892456: [88, 88]}

现在我想根据这本字典制作一个简单的图,如下所示:

test = {1092268: [x, y], 524292: [x, y], 892456: [x, y]}

所以我想我需要制作两个列表,即 x=[]y=[] 并且字典中列表的第一个值转到 x 和第二个到y。所以我最终得到一个点数为 (81,90) (80,80 和 (88,88) 的数字。我该怎么做?

最佳答案

使用 matplotlib 绘制数据

将数据转换为数字列表(类似数组)并使用 matplotlib.pyplot 中的 scatter() + annotate()

%matplotlib inline
import random
import sys
import array
import matplotlib.pyplot as plt

test = {1092268: [81, 90], 524292: [80, 80], 892456: [88, 88]}

# repackage data into array-like for matplotlib 
# (see a preferred pythonic way below)
data = {"x":[], "y":[], "label":[]}
for label, coord in test.items():
    data["x"].append(coord[0])
    data["y"].append(coord[1])
    data["label"].append(label)

# display scatter plot data
plt.figure(figsize=(10,8))
plt.title('Scatter Plot', fontsize=20)
plt.xlabel('x', fontsize=15)
plt.ylabel('y', fontsize=15)
plt.scatter(data["x"], data["y"], marker = 'o')

# add labels
for label, x, y in zip(data["label"], data["x"], data["y"]):
    plt.annotate(label, xy = (x, y))

scatter plot

可以通过阅读 docs 并添加更多配置来使情节更漂亮。


更新

采纳@daveydave400 的 answer 的建议。

# repackage data into array-like for matplotlib, pythonically
xs,ys = zip(*test.values())
labels = test.keys()   

# display
plt.figure(figsize=(10,8))
plt.title('Scatter Plot', fontsize=20)
plt.xlabel('x', fontsize=15)
plt.ylabel('y', fontsize=15)
plt.scatter(xs, ys, marker = 'o')
for label, x, y in zip(labels, xs, ys):
    plt.annotate(label, xy = (x, y))

关于Python 从字典中的值绘制图表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30013511/

相关文章:

python - 如何使用 Python Pyramid 处理多个数据库

Python:包含元组和长整数的列表

Swift - 是什么决定了字典集合的顺序?

Python:Rabin-Karp算法散列

python - 如何根据另一个列表中的项目从嵌套列表创建第三个列表

c++ - 循环列表 - 删除所有给定值

python - 调用存储在字典中的 lambda 时出现问题

python - 使用元组和字典

python - Sphinx matlab文档错误: missing module 'std'

html - 带有按钮的可扩展目录