如何用Pandas分组并在同一图表绘制苹果与橙子的价格时间趋势?
实现按水果分类绘制价格趋势折线图
嘿,刚学Pandas就能画出基础折线图已经很棒啦!想要把Apple和Orange的价格趋势分开成两条独立折线其实不难,我给你分享几种实用的方法,都是基于你提到的loc和分组思路,一步步来~
首先有个重要的小细节要先处理:你的PurchaseDate列目前是字符串格式,matplotlib没法正确识别时间顺序,所以第一步要把它转换成datetime类型,这样x轴的时间才会按顺序排列:
import pandas as pd import matplotlib.pyplot as plt filename = 'fruit-data.csv' fruits = pd.read_csv(filename) # 转换时间列格式 fruits['PurchaseDate'] = pd.to_datetime(fruits['PurchaseDate'])
方法一:用loc筛选单个水果数据
这是最直观的方法,直接筛选出Apple和Orange各自的数据,然后分别绘图:
plt.figure(figsize=(8,7)) plt.title('Purchase Date vs Price (Fruit-wise)') # 筛选Apple的数据并绘制折线 apple_data = fruits.loc[fruits['Fruit'] == 'Apple'] plt.plot(apple_data['PurchaseDate'], apple_data['Price'], label='Apple', marker='o', color='red') # 筛选Orange的数据并绘制折线 orange_data = fruits.loc[fruits['Fruit'] == 'Orange'] plt.plot(orange_data['PurchaseDate'], orange_data['Price'], label='Orange', marker='s', color='orange') # 完善图表细节 plt.xlabel('Time') plt.ylabel('Price') plt.legend() # 显示图例,区分两条线 plt.xticks(rotation=45) # 旋转x轴标签,避免文字重叠 plt.tight_layout() # 自动调整布局,防止标签被截断 plt.show()
方法二:用groupby分组批量处理
如果以后你的数据集里加入更多水果,这种方法会更省心——按Fruit分组后,遍历每个组自动绘图:
plt.figure(figsize=(8,7)) plt.title('Purchase Date vs Price (Fruit-wise)') # 按水果分组,遍历每个分组绘图 for fruit_name, group_data in fruits.groupby('Fruit'): plt.plot(group_data['PurchaseDate'], group_data['Price'], label=fruit_name, marker='.') # 完善图表细节 plt.xlabel('Time') plt.ylabel('Price') plt.legend() plt.xticks(rotation=45) plt.tight_layout() plt.show()
方法三:用pivot转宽格式后一键绘图
这是最简洁的方法,把数据转换成“时间为行,水果为列”的宽格式,然后直接调用pandas的plot方法:
# 转换为宽格式:每行是一个时间点,每列对应一种水果的价格 pivot_df = fruits.pivot(index='PurchaseDate', columns='Fruit', values='Price') plt.figure(figsize=(8,7)) # 在当前图表轴上绘制折线 pivot_df.plot(marker='.', ax=plt.gca()) plt.title('Purchase Date vs Price (Fruit-wise)') plt.xlabel('Time') plt.ylabel('Price') plt.xticks(rotation=45) plt.tight_layout() plt.show()
这几种方法都能实现你的需求,你可以根据自己的习惯选择~如果有其他细节想调整(比如颜色、标记样式),直接修改plt.plot里的参数就好啦!
内容的提问来源于stack exchange,提问作者DataVisNoob
相关产品推荐
相关产品推荐

