Python 从字典中的值绘制图形
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30013511/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python plot a graph from values inside dictionary
提问by Joel
I have a dictionary that looks like this:
我有一本看起来像这样的字典:
test = {1092268: [81, 90], 524292: [80, 80], 892456: [88, 88]}
Now I want to make a simple plot from this dictionary that looks like:
现在我想从这本字典中绘制一个简单的图,如下所示:
test = {1092268: [x, y], 524292: [x, y], 892456: [x, y]}
So i guess I need to make two lists i.e. x=[]
and y=[]
and the first value of the list in the dictionary goes to x and the second to y. So I end up with a figure with points (81,90) (80,80 and (88,88). How can I do this?
所以我想我需要制作两个列表,即x=[]
和y=[]
,字典中列表的第一个值到 x,第二个到 y。所以我最终得到一个点数 (81,90) (80,80 和 (88,88)。我该怎么做?
回答by Craig Burgler
def plot(label, x, y):
...
for (key, coordinates) in test.items():
plot(key, coordinates[0], coordinates[1])
回答by tmthydvnprt
Use matplotlibfor plotting data
使用matplotlib绘制数据
Transform the data into lists of numbers (array-like) and use scatter()
+ annotate()
from matplotlib.pyplot
.
将数据转换为数字列表(类似数组)并使用scatter()
+ annotate()
from matplotlib.pyplot
。
%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))
The plot can be made prettier by reading the docsand adding more configuration.
通过阅读文档并添加更多配置,可以使绘图更漂亮。
Update
更新
Incorporate suggestion from @daveydave400's answer.
纳入来自@daveydave400 的回答的建议。
# 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))
回答by djhoese
This works in both python 2 and 3:
这适用于python 2和3:
x, y = zip(*test.values())
Once you have these you can pass them to a plotting library like matplotlib.
一旦你有了这些,你就可以将它们传递给像 matplotlib 这样的绘图库。