2016-12-17 151 views
1

您好我有一个这样的数据帧绘制两个不同的数据框列:如何在时间基于相同的日期时间x轴

 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])等。我试图找出是否有一个快速的方法来完成它,而不需要完全操纵数据框。

回答

3

您可以简单地绘制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() 

enter image description here


如果你想在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() 
+0

不错!我想在不写每一行的情况下编写它,因为我必须使用许多列,但无论如何它都很好!我在木星笔记本上绘图,我问你是否有办法一个接一个地制作子图,而不是并排(我的意思是具有最大的x轴和小的y轴的图) –

+0

这是一个重要的信息应该成为问题的一部分。我更新了答案。 – ImportanceOfBeingErnest

+0

我尝试编辑代码,但我收到此行'ax.plot(df.Date,df [“Influenza [it]”],label =“Influenza [it]”)'的错误:'ValueError:invalid literal for float():2016-16'。如果我运行'df ['Date'] = pd.to_datetime(df ['Date'])'我收到此错误'ValueError:month必须在1..12' –