我有一个数据框,我想在三个子图中绘制。
索引是一个日期时间,因此x轴在子图中排列非常重要。
我的框架的一列仅包含一年中第一天的数据。其余的是nans。
以下是一个示例。
Cases Coverage Measles
2011-01-31 31.0 93.1 29.964546402502616
2011-02-28 43.68275418275418
2011-03-31 43.28153153153155
2011-04-30 37.25000000000002
2011-05-31 75.5229357798165
2011-06-30 48.727064220183486
2011-07-31 30.467948717948733
2011-08-31 31.286418094278353
2011-09-30 36.43205930461145
2011-10-31 31.816645136232765
2011-11-30 29.399802310147145
2011-12-31 31.34712643678163
2012-01-31 8.0 93.3 0.80327868852459
我想用非虚线连接非nan Cases
数据,但由于剩余月份的值为nan,因此不会绘制任何行。
知道怎么解决这个问题吗?
答案 0 :(得分:1)
from io import StringIO
import pandas as pd
txt = """date Cases Coverage Measles
2011-01-31 31.0 93.1 29.964546402502616
2011-02-28 nan nan 3.68275418275418
2011-03-31 nan nan 43.28153153153155
2011-04-30 nan nan 37.25000000000002
2011-05-31 nan nan 75.5229357798165
2011-06-30 nan nan 48.727064220183486
2011-07-31 nan nan 30.467948717948733
2011-08-31 nan nan 31.286418094278353
2011-09-30 nan nan 36.43205930461145
2011-10-31 nan nan 31.816645136232765
2011-11-30 nan nan 29.399802310147145
2011-12-31 nan nan 31.34712643678163
2012-01-31 8.0 93. 0.80327868852459
"""
df = pd.read_csv(StringIO(txt), delim_whitespace=True, index_col=0, parse_dates=[0])
# subset df with only columns that have nulls
dfna = df.loc[:, df.isnull().any()]
# plot the first df
ax = df.plot(marker='o')
# then fill in nulls with interpolate
# plot the result with dashed lines
dfna.interpolate('index').plot(ls='--', ax=ax)