在 python matplotlib 中绘制 (x, y) 坐标列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21519203/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:03:57  来源:igfitidea点击:

Plotting a list of (x, y) coordinates in python matplotlib

pythonmatplotlibplotcoordinates

提问by CodeKingPlusPlus

I have a list of pairs (a, b)that I would like to plot with matplotlibin python as actual x-y coordinates. Currently, it is making two plots, where the index of the list gives the x-coordinate, and the first plot's y values are the as in the pairs and the second plot's y values are the bs in the pairs.

我有一个(a, b)我想matplotlib在 python 中作为实际 xy 坐标绘制的对列表。目前,它正在制作两个图,其中列表的索引给出了 x 坐标,第一个图的 y 值是a成对中的s,第二个图的 y 值是b成对中的s。

To clarify, my data looks like this: li = [(a,b), (c,d), ... , (t, u)]I want to do a one-liner that just calls plt.plot()incorrect. If I didn't require a one-liner I could trivially do:

澄清一下,我的数据如下所示:li = [(a,b), (c,d), ... , (t, u)]我想做一个单线,只是调用plt.plot()不正确。如果我不需要单线,我可以简单地做:

xs = [x[0] for x in li]
ys = [x[1] for x in li]
plt.plot(xs, ys)
  • How can I get matplotlib to plot these pairs as x-y coordinates?
  • 如何让 matplotlib 将这些对绘制为 xy 坐标?

Thanks for all the help!

感谢所有的帮助!

采纳答案by sashkello

As per this example:

根据这个例子

import numpy as np
import matplotlib.pyplot as plt

N = 50
x = np.random.rand(N)
y = np.random.rand(N)

plt.scatter(x, y)
plt.show()

will produce:

将产生:

enter image description here

在此处输入图片说明

To unpack your data from pairs into lists use zip:

要将您的数据从成对中解压缩到列表中,请使用zip

x, y = zip(*li)

So, the one-liner:

所以,单线:

plt.scatter(*zip(*li))

回答by Shubham Rana

If you want to plot a single line connecting all the points in the list

如果您想绘制一条连接列表中所有点的线

plt . plot ( li [ : ] )

plt . show ( )

This will plot a line connecting all the pairs in the list as points on a Cartesian plane from the starting of the list to the end. I hope that this is what you wanted.

这将绘制一条连接列表中所有对的线,作为笛卡尔平面上从列表开始到结束的点。我希望这就是你想要的。

回答by Zweedeend

If you have a numpy array you can do this:

如果你有一个 numpy 数组,你可以这样做:

import numpy as np
from matplotlib import pyplot as plt

data = np.array([
    [1, 2],
    [2, 3],
    [3, 6],
])
x, y = data.T
plt.scatter(x,y)
plt.show()