以多种颜色绘制单条线

Plot a single line in multiple colors

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns

rng = np.random.default_rng()

data = pd.DataFrame({
    'group': pd.Categorical(['a', 'b', 'b', 'a', 'a', 'a', 'b', 'b']),
})
data['value'] = rng.uniform(size=len(data))

使用 Matplotlib 或 Seaborn,是否有直接的方法将此数据绘制为单条线,但线的颜色根据 group?只要颜色一致,两点之间的确切颜色变化并不重要。

您可以制作一个颜色字典并在 for 循环中绘制相邻点之间的线:

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

rng = np.random.default_rng()

data = pd.DataFrame({
    'group': pd.Categorical(['a', 'b', 'b', 'a', 'a', 'a', 'b', 'b']),
})
colours = {'a': 'red', 'b':'blue'}
data['value'] = rng.uniform(size=len(data))
plt.figure()
for i in range(len(data['value'])-1):
    plt.plot([i, i+1],[data['value'][i], data['value'][i+1]], color=colours[data['group'][i]])
plt.show()

输出:

我不知道这是否符合“直截了当”的条件,但是:

from matplotlib.lines import Line2D
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

rng = np.random.default_rng()

data = pd.DataFrame({
    'group': pd.Categorical(['a', 'b', 'b', 'a', 'a', 'a', 'b', 'a']),
})
data['value'] = rng.uniform(size=len(data))

f, ax = plt.subplots()

for i in range(len(data)-1):
    ax.plot([data.index[i], data.index[i+1]], [data['value'].iat[i], data['value'].iat[i+1]], color=f'C{data.group.cat.codes.iat[i]}', linewidth=2, marker='o')

# To remain consistent, the last point should be of the correct color. 
# Here, I changed the last point's group to 'a' for an example.
ax.plot([data.index[-1]]*2, [data['value'].iat[-1]]*2, color=f'C{data.group.cat.codes.iat[-1]}', linewidth=2, marker='o')    

legend_lines = [Line2D([0], [0], color=f'C{code}', lw=2) for code in data['group'].unique().codes]
legend_labels = [g for g in data['group'].unique()]
plt.legend(legend_lines, legend_labels, title='group')
plt.show()

这导致: