【问题标题】:How to plot two different dataframe columns at time based on the same datetime x-axis如何基于相同的日期时间 x 轴在时间绘制两个不同的数据框列
【发布时间】:2017-05-03 03:14:21
【问题描述】:

您好,我有一个这样的数据框:

        Date  Influenza[it]  Febbre[it]  Cefalea[it]  Paracetamolo[it]  \
0    2008-01            989        2395         1291              2933   
1    2008-02            962        2553         1360              2547   
2    2008-03           1029        2309         1401              2735   
3    2008-04           1031        2399         1137              2296    

     Unnamed: 6 tot_incidence  
0           NaN          4.56  
1           NaN          5.98  
2           NaN          6.54  
3           NaN          6.95  

我想用 x 轴上的 Date 列和 y 轴上的 Influenza[it] 列和另一列像 Febbre[it] 绘制不同的数字。然后再次x轴Date列,y轴Influenza[it]列和另一列(例如Paracetamolo[it])等等。我试图弄清楚是否有一种快速的方法可以在不完全操纵数据帧的情况下实现它。

【问题讨论】:

    标签: python datetime pandas plot dataframe


    【解决方案1】:

    您可以简单地绘制 3 个不同的子图。

    import pandas as pd
    import matplotlib.pyplot as plt
    
    dic = {"Date" : ["2008-01","2008-02", "2008-03", "2008-04"],
           "Influenza[it]" : [989,962,1029,1031],
            "Febbre[it]" : [2395,2553,2309,2399],
            "Cefalea[it]" : [1291,1360,1401,1137],
            "Paracetamolo[it]" : [2933,2547,2735,2296]}
    
    df = pd.DataFrame(dic)
    #optionally convert to datetime
    df['Date'] = pd.to_datetime(df['Date'])
    
    fig, ax = plt.subplots(1,3, figsize=(13,7))
    df.plot(x="Date", y=["Influenza[it]","Febbre[it]" ], ax=ax[0])
    df.plot(x="Date", y=["Influenza[it]","Cefalea[it]" ], ax=ax[1])
    df.plot(x="Date", y=["Influenza[it]","Paracetamolo[it]" ], ax=ax[2])
    
    #optionally equalize yaxis limits
    for a in ax:
        a.set_ylim([800, 3000])
    
    plt.show()
    


    如果您想在 jupyter 笔记本中分别绘制每个图,则以下内容可能会满足您的需求。
    此外,我们将日期从格式 year-week 转换为日期时间,以便能够使用 matplotlib 绘制它们。
    %matplotlib inline
    import pandas as pd
    import matplotlib.pyplot as plt
    
    dic = {"Date" : ["2008-01","2008-02", "2008-03", "2008-04"],
           "Influenza[it]" : [989,962,1029,1031],
            "Febbre[it]" : [2395,2553,2309,2399],
            "Cefalea[it]" : [1291,1360,1401,1137],
            "Paracetamolo[it]" : [2933,2547,2735,2296]}
    
    df = pd.DataFrame(dic)
    #convert to datetime, format year-week -> date (monday of that week)
    df['Date'] = [ date + "-1" for date in df['Date']] # add "-1" indicating monday of that week
    df['Date'] = pd.to_datetime(df['Date'], format="%Y-%W-%w")
    
    cols = ["Febbre[it]", "Cefalea[it]", "Paracetamolo[it]"]
    for col in cols:
        plt.close()
        fig, ax = plt.subplots(1,1)
        ax.set_ylim([800, 3000])
        ax.plot(df.Date, df["Influenza[it]"], label="Influenza[it]")
        ax.plot(df.Date, df[col], label=col)
        ax.legend()
        plt.show()
    

    【讨论】:

    • 不错!我不想每次都写一行,因为我必须使用很多列,但无论如何它都很好!我在 jupiter 笔记本上绘图,我问你是否有办法让子图一个接一个而不是并排(我的意思是 x 轴最大和 y 轴小的数字)
    • 这是一个重要的信息,应该是问题的一部分。我更新了答案。
    • 我尝试使用编辑过的代码,但我收到了这一行的错误 'ax.plot(df.Date, df["Influenza[it]"], label="Influenza[it]")' :'ValueError:float()的无效文字:2016-16'。如果我运行 'df['Date'] = pd.to_datetime(df['Date'])' 我收到此错误 'ValueError: month must be in 1..12'
    • 对不起,我忘了删除评论:使用 matplotib 您需要使用日期时间 - 它不再是可选的。您得到的错误是有道理的,因为“2016-16”不是有效日期。您是否期望 matplotlib 在一年中创造 4 个新月份,还是我误解了您使用的日期时间格式?
    • 嗯,那是.. 另一条信息应该是问题的一部分。您的数据是否涵盖数年?日期是否等距,即第一个条目和最后一个条目之间的每周是否存在?您希望日期轴以周为单位还是以正常日期为单位(例如该特定周的每个星期一)?
    猜你喜欢
    • 1970-01-01
    • 2016-07-17
    • 1970-01-01
    • 2022-11-30
    • 1970-01-01
    • 2019-08-31
    • 2020-07-18
    • 2014-06-02
    • 1970-01-01
    相关资源
    最近更新 更多