【问题标题】:Multiple plots on one graph from DataFrame来自 DataFrame 的一张图上的多个图
【发布时间】:2017-06-27 18:25:30
【问题描述】:

我有以下数据框:

    Food               Men     Women    Year
0   Apples as fruit    89.18    90.42   1994
1   Berries            84.21    81.73   1994
2   Grapes             88.79    88.13   1994
3   Melons             80.74    84.96   1994
4   Oranges, Total     85.66    89.77   1994
5   Other citrus fruit 79.82    80.64   1994
6   Stone fruit        88.95    89.55   1994
7   Tropical fruit     74.61    80.40   1994
8   Apples as fruit    90.86    91.21   1994
9   Berries            88.57    88.29   2004
10  Grapes             88.55    90.14   2004
11  Melons             79.72    80.99   2004
12  Oranges, Total     84.46    88.07   2004
13  Other citrus fruit 73.74    69.60   2004
14  Stone fruit        94.02    87.94   2004
15  Tropical fruit     74.58    85.85   2004

我正在尝试创建水果与年份或时间的线图,其中食物为不同的线条颜色。按照答案here 并使用groupby,我尝试了以下操作:

for i, group in fruits.groupby('Food'):
   plt.figure()
   group.plot(x='Year', y='Men', title=str(i))

但这会产生 8 个带有一条线的图形,或者每个水果一个图形。我想要一个图表,每个水果都有不同的线。我将如何使用 pandas、matplotlib 或 numpy 来做到这一点?此外,当前 int 中的年份列,因此该图包括 1996 年、1998 年、2000 年等年份,我没有数据。我的意思是它是一个像 1993-1994 或 2003-2004 这样的范围。有什么办法可以省略吗?

【问题讨论】:

    标签: python-3.x pandas numpy matplotlib


    【解决方案1】:

    您需要在循环之外创建图形。然后最好使用 ax 关键字参数为 Dataframe 图提供一个 matplotlib 轴。

    import pandas as pd
    import matplotlib.pyplot as plt
    
    year=[1994,1994,1994,2000,2000,2000,2006,2006,2006]
    fr = ["Apple", "Banana", "Cherry"]*3
    men = [1,6,6,3,5,8,7,2,7]
    fruits =pd.DataFrame({"Year" : year, "Food" : fr, "Men" : men})
    
    fig, ax = plt.subplots()
    for i, group in fruits.groupby('Food'):
        group.plot(x='Year', y='Men', ax=ax, label=group["Food"].iloc[0])
    ax.set_title("Food")
    ax.set_ylabel("Men")
    #optionally only set ticks at years present in the years column
    ax.set_xticks(fruits["Year"].unique())
    
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 2023-03-12
      • 1970-01-01
      • 2018-03-08
      • 2023-01-31
      • 2017-11-01
      • 2016-07-08
      • 2012-02-05
      • 2016-11-02
      • 1970-01-01
      相关资源
      最近更新 更多