如何基于同一个datetime xaxis同时绘制两个不同的dataframe列

2024-10-02 12:31:27 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,我有这样一个数据帧:

        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])等。我想知道是否有一种快速的方法可以在不完全操纵数据帧的情况下实现它。在


Tags: 数据方法图形date绘制情况itnan
1条回答
网友
1楼 · 发布于 2024-10-02 12:31:27

您可以简单地绘制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绘制它们。 ^{pr2}$

相关问题 更多 >

    热门问题