首页 > 解决方案 > 在两个绘图之间共享 x 轴

问题描述

我有以下时间序列,ts索引和列名为metric_value

ts
2020-01-01 00:00:00    1225917
2020-01-01 01:00:00     670334
2020-01-01 02:00:00     668207
2020-01-01 03:00:00     576977
2020-01-01 04:00:00     713490
Name: metric_value, dtype: int32

我正在尝试绘制这个时间序列并用红色圆圈标记异常数据点。异常值的索引在此列表中:

idxs=['2020-06-06 19:00:00', '2020-07-04 19:00:00', '2020-08-08 19:00:00']

下面显示了我如何绘制六月的数据。

fig, ax = plt.subplots(1, 1, sharex="all", sharey="all", figsize=(12,4))
ax = ts.loc['2020-06-01 00:00:00':'2020-06-30 23:00:00']['metric_value'].plot(title='June')
ax = ts.loc[[idx for idx in idxs if idx>'2020-06-01 00:00:00' and idx<'2020-06-30 23:00:00']]['metric_value'].plot(style='.')

plt.xticks(rotation=45)
plt.ylim(bottom=0)

对于 6 月份,这个 index= 有一个异常值2020-06-06 19:00:00。问题是该图未在正确位置显示此数据点。它显示在第一个位置为零!我认为这是因为这两个图不共享 x 轴,并且该图仅显示第二个图的轴。我该如何解决?我尝试了这个解决方案,但没有奏效!

在此处输入图像描述

标签: pythonpandasdataframematplotlibtime-series

解决方案


我解决了以下问题:

ts['flag'] = False
for idx in idxs:
   ts.loc[idx, 'flag'] = True
    
x = list(np.where(ts.loc['2020-06-01 00:00:00':'2020-06-30 23:00:00']['flag'])[0])
y = ts.iloc[np.where(ts.loc['2020-06-01 00:00:00':'2020-06-30 23:00:00']['flag'])]['metric_value']    
    
ts.loc['2020-06-01 00:00:00':'2020-06-30 23:00:00']['metric_value'].plot(title='June', figsize=(12,4), x_compat=True)
if len([idx for idx in idxs if idx>'2020-06-01 00:00:00' and idx<'2020-06-30 23:00:00'])>0:
    plt.plot(x, y, 'ro', markersize=4,)

plt.xticks(rotation=45)
plt.ylim(bottom=0)

推荐阅读