I have a list of pairs (a, b)
that I would like to plot with matplotlib
in 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 a
s in the pairs and the second plot's y values are the b
s in the pairs.
我有一个对(a, b)的列表,我想用python中的matplotlib作为实际的x-y坐标。目前,它正在做两个图,其中列表的索引给出了x坐标,第一个图的y值是成对的,第二个图的y值是对的b。
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),…我想做一个只叫pl .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来把这些对作为x-y坐标?
Thanks for all the help!
谢谢你的帮助!
3 个解决方案
#1
87
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:
会产生:
To unpack your data from pairs into lists use zip
:
要将你的数据从成对打开到列表,请使用zip:
x, y = zip(*li)
So, the one-liner:
所以,一行程序:
plt.scatter(*zip(*li))
#2
11
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)
#3
-1
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.
这将绘制一条线,将列表中的所有对点连接到从列表开始到结束的笛卡尔平面上的点。我希望这就是你想要的。
#1
87
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:
会产生:
To unpack your data from pairs into lists use zip
:
要将你的数据从成对打开到列表,请使用zip:
x, y = zip(*li)
So, the one-liner:
所以,一行程序:
plt.scatter(*zip(*li))
#2
11
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)
#3
-1
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.
这将绘制一条线,将列表中的所有对点连接到从列表开始到结束的笛卡尔平面上的点。我希望这就是你想要的。