基于标签颜色编码绘制DataFrame行数据折线图的问题
按标签统一配色绘制行级折线图
需求:将数据集的每行绘制成折线图(共6条线),按照Label值统一设置颜色:Label 0为蓝色,Label 1为红色。
示例数据集:
Label,col1,col2,col3 0,43.55,98.86,2.34 1,21.42,51.42,71.05 0,49.17,13.55,101.00 0,5.00,17.88,28.00 1,44.00,2.42,34.69 1,41.88,144.00,9.75
尝试过的代码:
df = pd.read_csv(dfname,header=0) df.index = df['Label'] # index the label df_T = df.iloc[:,1:].T # remove the label transpose the df
转置后使用df_T.plot.line()绘图时,每个列(对应原数据行)会被分配独立颜色,无法实现按Label统一配色。
解决方案1:使用Matplotlib手动循环绘制
直接遍历每行数据,根据Label值指定颜色绘制折线:
import pandas as pd import matplotlib.pyplot as plt # 读取数据 df = pd.read_csv(dfname, header=0) # 定义标签与颜色的映射 color_map = {0: 'blue', 1: 'red'} # 创建画布 plt.figure(figsize=(10, 6)) # 遍历每行绘制折线 for idx, row in df.iterrows(): # 提取当前行的数值列和标签 plot_values = row[['col1', 'col2', 'col3']] current_label = row['Label'] # 绘制折线,指定颜色与图例标签 plt.plot(plot_values.index, plot_values.values, color=color_map[current_label], label=f'Row {idx} (Label {current_label})') # 配置图表元素 plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left') plt.title('Line Plots Grouped by Label Color') plt.xlabel('Columns') plt.ylabel('Value') plt.tight_layout() plt.show()
解决方案2:基于Pandas Plot指定颜色列表
利用原数据的Label顺序生成对应颜色列表,传给Pandas的绘图方法:
import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv(dfname, header=0) df_T = df.iloc[:,1:].T # 根据原数据的Label生成对应的颜色列表 line_colors = ['blue' if label == 0 else 'red' for label in df['Label']] # 绘图时传入颜色列表 ax = df_T.plot.line(color=line_colors, figsize=(10, 6)) ax.set_title('Line Plots Grouped by Label Color') ax.set_xlabel('Columns') ax.set_ylabel('Value') plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left') plt.tight_layout() plt.show()
内容的提问来源于stack exchange,提问作者bapors
相关产品推荐
相关产品推荐

