如何基于Label分组,用Matplotlib绘制DataFrame中Data1与Data2的对比图
问题描述
我有一个核心包含3列的DataFrame(实际列数更多):df["Label","Data1","Data2"],数据如下:
import pandas as pd import matplotlib.pyplot as plt df = pd.DataFrame({'Label': [1, 1, 1, 2, 2, 3, 3, 3, 4, 4], 'Data1': [0.1, 0.01, 0.15, 0.3, 0.35, 0.38, 0.44, 0.45, 0.8, 0.88], 'Data2': [1.4, 1.4, 1.6, 2.3, 2.5, 3.6, 3.8, 3.9, 7.3, 7.7]})
我想要绘制Data1与Data2的对比图(即Data1为横轴,Data2为纵轴),同时基于Label列分组,不同分组用不同颜色。尝试了以下代码但未得到预期结果:
df.groupby("Label")[ ["Data1","Data2"] ].plot(marker='.',subplots=False,ax=plt.gca())
另外想了解是否可以用Matplotlib实现该需求。
解决方案
一、调整Pandas代码实现
你之前的代码问题在于:groupby后直接调用plot会默认把每个分组的Data1和Data2作为两条折线按行索引绘制,而非Data1 vs Data2的对比图。正确做法是按Label分组后,对每个分组绘制散点图(或折线图,若需要连接同组点):
散点图版本
# 定义颜色映射,对应不同Label color_map = {1: 'red', 2: 'blue', 3: 'green', 4: 'orange'} fig, ax = plt.subplots() # 遍历每个分组 for label, group in df.groupby('Label'): group.plot(kind='scatter', x='Data1', y='Data2', marker='.', color=color_map[label], label=f'Label {label}', ax=ax) ax.set_xlabel('Data1') ax.set_ylabel('Data2') ax.set_title('Data1 vs Data2 (Grouped by Label)') plt.legend() plt.show()
折线图版本(同组点连接)
如果需要把同Label的点用线连接起来,只需把kind='scatter'改成kind='line',同时保留marker:
fig, ax = plt.subplots() for label, group in df.groupby('Label'): group.plot(kind='line', x='Data1', y='Data2', marker='.', color=color_map[label], label=f'Label {label}', ax=ax) ax.set_xlabel('Data1') ax.set_ylabel('Data2') ax.set_title('Data1 vs Data2 (Grouped by Label)') plt.legend() plt.show()
二、纯Matplotlib实现
完全用Matplotlib也可以实现,核心逻辑是筛选每个Label对应的数据,然后逐个绘制:
color_map = {1: 'red', 2: 'blue', 3: 'green', 4: 'orange'} labels = df['Label'].unique() fig, ax = plt.subplots() for label in labels: # 筛选当前Label的数据 subset = df[df['Label'] == label] # 绘制散点图 ax.scatter(subset['Data1'], subset['Data2'], marker='.', color=color_map[label], label=f'Label {label}') # 如果需要折线连接,取消下面注释 # ax.plot(subset['Data1'], subset['Data2'], # color=color_map[label], linestyle='-') ax.set_xlabel('Data1') ax.set_ylabel('Data2') ax.set_title('Data1 vs Data2 (Grouped by Label)') plt.legend() plt.show()
内容的提问来源于stack exchange,提问作者user8268123
相关产品推荐
相关产品推荐

