python - 在两个绘图之间共享 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 轴,并且该图仅显示第二个图的轴。我该如何解决?我尝试了这个解决方案,但没有奏效!
解决方案
我解决了以下问题:
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)
推荐阅读
- javascript - 如何在 Matlab/Python/JS 中获取形状(/Body)的 X、Y(和 Z)坐标?
- cmake - 如何将没有价值的参数传递给 CMake?
- r - 这是 R 神经网络过拟合吗?
- c# - 特定字符之前的 C# 文本
- java - 将方法的返回值作为参数传递给同一类中的另一个方法
- ios - Swift 4 - PDFAnnotation 文本(或 UITextField)是文本的大小
- android - 恢复旧应用的应用id(Eclipse时代)
- android - 无法解析符号“LocalBroadcastManager”
- ios - 在 iOS PWA 中从 jsPDF 下载 PDF
- algorithm - 如何以最佳方式将元素放置在矩阵中,以使与其他元素的距离最小?