[英]How to plot 2D data points with color according to third column value
Suppose I have an array with three columns: 假设我有一个包含三列的数组:
>>>print(arr)
array(
[[1 2 -1]
[1 3 1]
[3 2 -1]
[5 2 -1]]
)
Suppose I want to turn this into a scatter plot: 假设我想将其转换为散点图:
plt.plot(arr[:,0], arr[:,1], 'xr')
Works fine. 工作正常。 But, all the scattered points look like a red 'x' .
但是,所有散乱的点看起来像一个红色的'x' 。 Suppose I want to have a red 'x' if the third column value is -1, and a blue 'o' if the value is 1. How do I do that?
假设我想要第三列值为-1时为红色'x',如果值为1则为蓝色'o' 。我该怎么做?
Is this possible to achieve with plt.plot()
? 这是用
plt.plot()
实现的吗?
If you want to change the color and the marker, you need to plot several scatter plots, at least one for each marker. 如果要更改颜色和标记,则需要绘制多个散点图,每个标记至少一个。
import matplotlib.pyplot as plt
import numpy as np
a = np.array([[1, 2, -1],
[1, 3, 1],
[3, 2, -1],
[5, 2, -1]])
mapping= {-1: ("red", "x"), 1: ("blue", "o")}
for c in np.unique(a[:,2]):
d = a[a[:,2] == c]
plt.scatter(d[:,0], d[:,1], c=mapping[c][0], marker=mapping[c][1])
#plt.plot(d[:,0], d[:,1], color=mapping[c][0], marker=mapping[c][1])
plt.show()
Using a plot
is equally possible (see commented line in code). 同样可以使用
plot
(请参阅代码中的注释行)。
Iterate through your list, and consider that the 3rd item of each sublist is the color. 遍历您的列表,并考虑每个子列表的第3项是颜色。 Attribute the color according to the data you have.
根据您拥有的数据对颜色进行属性化。 Here, I assign the value
'r'
to c
if c == -1
, else, it will be equal to 'b'
, meaning blue . 在这里,如果
c == -1
,我将值'r'
赋值给c
,否则,它将等于'b'
,意思是蓝色 。
from matplotlib import pyplot as plt
arr = [[1, 2, -1], [1, 3, 1], [3, 2, -1], [5, 2, -1]]
for x, y, color in arr:
c = 'r' if color == -1 else 'b'
plt.plot(x, y, 'x' + c)
plt.show()
as a fellow Python beginner I have had a similar question recently and for me the best solution was to use the fantastic " seaborn " package. 作为一名Python初学者,我最近遇到了类似的问题,对我而言,最好的解决方案是使用梦幻般的“ seaborn ”软件包。
The trick is to combine Pandas ' DataFrame ' and Seaborn's " FacetGrid " objects and let them do all the work. 诀窍是结合Pandas的DataFrame和Seaborn的“ FacetGrid ”对象,让他们完成所有工作。 Here's how I did it for your particular example:
以下是我为您的特定示例所做的工作:
Here is my code: 这是我的代码:
import seaborn as sns
import pandas as pd
a = pd.DataFrame(
[[1, 2, -1],
[1, 3, 1],
[3, 2, -1],
[5, 2, -1]])
a.columns=['A','B','C']
sns.FacetGrid(a, hue="C", size=2).map(plt.scatter, "A", "B").add_legend()
plt.show()
Voila ! 瞧!
Obviously this is a trivial example, but with real data the result is great and easy to reproduce (see below) 显然这是一个简单的例子,但是使用真实数据,结果非常好且易于重现(见下文)
PS: This is my very first post on stackoverflow - it feels like the beginning of something PS:这是我在stackoverflow上的第一篇文章 - 感觉就像是某事的开始
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.