如何将颜色线段基于字符串/其他列的值?

时间:2019-02-11 06:53:27

标签: python dataframe matplotlib

具有3列的数据框

x       y     type
21/02   5     'a'
22/02   6     'b'
...   ...   ...

总共我有两种类型:'a' and 'b'

基于stackoverflow questionmatplotlib documentation,我有以下内容:

fig, ax = plt.subplots()   
xy = np.column_stack((df['x'],df['y'])) 
xy = xy.reshape(-1, 1, 2) 
segments = np.hstack([xy[:-1], xy[1:]]) 
coll = LineCollection(segments, color='r') 
ax.add_collection(coll)
plt.show()

这给了我下面的图:

enter image description here

我认为我必须采取以下措施:coll.set_array(some_value) 但是我不知道如何。

我走了这么远: 我使用了与上面相同的代码,但只更改了一行:

coll = LineCollection(segments,cmap=plt.cm.gist_ncar)

enter image description here

但是现在这些段的颜色是随机的。

如何将分段的颜色基于数据框中的“类型”列?

1 个答案:

答案 0 :(得分:2)

如果只有两种颜色,这应该可以工作:

flight_combination

要获得更多颜色,您可以通过类似的方式将类型映射到颜色列表。