首页 > 解决方案 > 为什么python情节会延长到明年?如何停止最后的数据?(熊猫,matplotlib)

问题描述

两者都resample导致groupby生成的线图延长到明年 1 月。如何使用最后一个数据停止绘图以更清楚地查看我实际拥有的数据?

这是代码和结果图。

# import painkiller data
import pandas as pd
import matplotlib.pyplot as plt
#import plotly.plotly as py
df = pd.read_csv('/Users/user/Documents/health/PainOverTime.csv',delimiter=',',header=0)
# plot bar graph of date and painkiller amount
times = pd.to_datetime(df.loc[:,'Time'])

# raw plot of data
ts = pd.Series(df.loc[:,'acetaminophen'].values, index = times,
               name = 'Painkiller over Time')

# combine data by day
#groupby method
ts1 = df.groupby(times.dt.date)['acetaminophen'].sum()
fig1 = ts1.plot()
# resample method
ts2 = ts.resample('D').sum()
plt.figure()
fig2 = ts2.plot()

代码中的图

标签: pythonpandasdatetimematplotlibpandas-groupby

解决方案


像这样的东西应该可以解决问题:

plt.xlim(None, last_index_you_want)

或者set_xlim


推荐阅读