【问题标题】:Sharing x-axis between two plots在两个绘图之间共享 x 轴
【发布时间】:2021-03-14 05:38:00
【问题描述】:

我有以下时间序列,以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 月份,该指数有一个异常值=2020-06-06 19:00:00。问题是该图未在正确位置显示此数据点。它显示在第一个位置为零!我认为这是因为这两个图不共享 x 轴,并且该图仅显示第二个图的轴。我该如何解决? 我试过this solution,但没用!

【问题讨论】:

标签: python pandas dataframe matplotlib time-series


【解决方案1】:

在潘达斯图中设置两个轴可以通过以下方式实现以下答案是否解决了您的问题?

import pandas as pd
import numpy as np

date_rng = pd.date_range('2020-01-01', '2020-09-30', freq='1H')
value = np.random.randint(5000, 30000, size=6553)
ts = pd.DataFrame({'ts': pd.to_datetime(date_rng), 'metric_value':value})
ts.set_index('ts', inplace=True)
import matplotlib.pyplot as plt

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, sharey="all", figsize=(12,4))
ts.loc['2020-06-01 00:00:00':'2020-06-30 23:00:00',['metric_value']].plot(title='June')
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='.', secondary_y=['ts', 'metric_value'])

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

plt.show()

【讨论】:

  • 不,它不起作用 :( 仍然在 x=0 上绘制点
  • 你复制并运行了我所有的代码吗?如果仍然出现错误,可能是环境问题?
【解决方案2】:

我解决了如下问题:

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)

【讨论】:

    猜你喜欢
    • 2010-11-27
    • 2022-11-24
    • 2021-12-15
    • 2019-02-03
    • 1970-01-01
    • 1970-01-01
    • 2019-05-01
    • 2019-09-03
    • 2019-07-13
    相关资源
    最近更新 更多