【问题标题】:Line plot x axis using pandas python使用pandas python的线图x轴
【发布时间】:2020-01-06 20:43:09
【问题描述】:

结果

   year  Month  Min_days    Avg_days    Median_days     Count
    2015   1          9        12.56666666          10         4
    2015   2          10       13.67678788          9          3    
   ........................................................
    2016   12       12       15.7889990           19          2
    and so on...

我希望创建一个绘制 min_days、avg_days、median_days 的线图,并根据月份和年份进行计数。我该怎么做呢

到目前为止尝试的代码

axes = result.plot.line(subplots=True)
type(axes)

这很好用,但我也得到了年份和月份的子图。我希望年份和月份在 x 轴上

Code2 试过:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
result.groupby('Year').plot(x='Year', y='Median_days', ax=ax, legend=False)

此代码的问题是它仅 groupbys 一年。我也需要一个月(2015 年 1 月、2015 年 2 月等)。另一个问题是这给了我一个中位数的子图。如何为均值、最小值等添加子图

编辑: 附言此外,如果有人可以回答月份 int 被月份名称替换(Jan、Feb 等),那就太好了

【问题讨论】:

    标签: python pandas plot line


    【解决方案1】:

    一种解决方案可能是首先创建一个年月列:

    result["year-month"] = pd.to_datetime(
        result.year.astype(str) + "-" + result.Month.astype(str)
    )
    
    fig, ax = plt.subplots()
    for col in ["Min_days", "Avg_days", "Median_days", "Count"]:
        ax.plot(result["year-month"], result[col], label=col)
    ax.legend(loc="best")
    ax.tick_params(axis="x", rotation=30)
    

    利用您提供给我们的有限数据,您将获得:

    【讨论】:

    • 您好,抱歉,该列是月份名称而不是月份。此外,年和月名称是索引而不是列名,因为结果是 groupby 输出。所以我得到的错误是关键字错误:Year
    • @ShailajaGuptaKapoor 然后先执行.reset_index(),然后将.month 更改为['Month Name']
    • 我应该在哪里重置索引?你的意思是这样的:result = result.reset_index()?
    • 文件 "",第 7 行 result.Year.astype(str) + "-" + result.['Month Name'].astype(str) ^ SyntaxError: 无效语法
    • 现在编辑问题以反映原创'
    猜你喜欢
    • 2021-12-12
    • 1970-01-01
    • 2020-05-23
    • 2020-08-22
    • 2014-01-23
    • 2017-10-28
    相关资源
    最近更新 更多