如何将 Linecollection 实现到数据框以用不同颜色为一条线着色?

How to implement Linecollection to dataframe to color one line with different color?

我需要根据条件用不同颜色的线条绘制子图。 为此,我尝试使用 LineCollection。但是对于我的数据,我收到错误并且无法找到如何将它用于我的数据的方法。我用这个堆栈堆叠,有人可以给我提示如何让它工作吗?

接下来看我的数据:

age_gps_data ref_station_id river_km    
1.0     2421.0          667.5144925407869   
0.5     2421.0          667.5144592533758   
1.0     2421.0          667.5144249505418   
0.5     2421.0          667.5143958295257   
1.0     2421.0          667.5143629441299   
0.5     2421.0          667.5143266152246   
1.0     2.0     667.5142970594003   
0.5     2.0     667.5142580343961   
1.0     2.0     667.5142211073334   
0.5     2.0     667.5141878187346   

我尝试了这个解决方案,但出现错误:

 filename = "G:\ais_evaluation\track_AIS_2route.csv"
 df2 = pd.read_csv(filename, delimiter=';')

 segments = []
 color = np.zeros(shape=(10,4))
 x = df2['river_km'].tolist()
 y = df2['age_gps_data'].tolist()

 i = 0
 z = df2.ref_station_id

 for x1, y1, x2, y2 in zip(x, x[1:], y, y[1:]):

    if z == 2.0:
       color[i] = colors.to_rgba('Crimson')
    else:
        color[i] = colors.to_rgba('slategray')
    segments.append([(x1, y1), (x2, y2)])
    i += 1 

 lc = mc.LineCollection(segments, colors=color, linewidths=2)
 fig, ax = pl.subplots()
 ax.add_collection(lc)
 ax.autoscale()
 ax.margins(0.1)
 pl.show()     

我有这个错误:

 ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(

我应该如何改进此代码以根据参数 ref_station_id 实现具有不同颜色的 river_km 与 age_gps_data 行? 我是 python 的新人,非常感谢任何帮助。

您的问题来自 if z == 2.0: 行。这里 z 是一个 pandas 系列 df2.ref_station_id) 因此它不能等于 2.0.

我没有完全遵循你代码的逻辑,所以我不能肯定地告诉你该怎么做,但看起来你需要在 z 的同时遍历 z 的值=15=] 和 y 并测试 z 而不是 z 本身的后续值是否等于 2.0

例如:

for x1, y1, x2, y2, z0 in zip(x, x[1:], y, y[1:], z):
    if z0 == 2.0:
    (...)

编辑 这是完整的功能代码:

import matplotlib.pyplot as plt
from matplotlib import colors
from matplotlib import collections as mc
from io import StringIO

d = """age_gps_data ref_station_id river_km    
1.0     2421.0          667.5144925407869   
0.5     2421.0          667.5144592533758   
1.0     2421.0          667.5144249505418   
0.5     2421.0          667.5143958295257   
1.0     2421.0          667.5143629441299   
0.5     2421.0          667.5143266152246   
1.0     2.0     667.5142970594003   
0.5     2.0     667.5142580343961   
1.0     2.0     667.5142211073334   
0.5     2.0     667.5141878187346   
"""
df2 = pd.read_csv(StringIO(d), delimiter='\s+')

segments = []
color = np.zeros(shape=(10,4))
x = df2['river_km'].tolist()
y = df2['age_gps_data'].tolist()

i = 0
z = df2.ref_station_id

for x1, y1, x2, y2, z0 in zip(x, y, x[1:], y[1:], z):
    if z0 == 2.0:
        color[i] = colors.to_rgba('Crimson')
    else:
        color[i] = colors.to_rgba('slategray')
    segments.append([(x1, y1), (x2, y2)])
    i += 1 

lc = mc.LineCollection(segments, colors=color, linewidths=2)
fig, ax = plt.subplots()
ax.add_collection(lc)
ax.autoscale()
ax.margins(0.1)
plt.show()