使用sharex的不同x值

时间:2017-08-07 14:59:25

标签: pandas matplotlib

我有两个时间索引系列,我想绘制它们并共享x轴(FEATURE的范围包含X的范围):

import pandas as pd
import matplotlib.pyplot as plt
import datetime

start = pd.Timestamp('2017-01-01 08:00:00')
end = pd.Timestamp('2017-01-01 10:00:00')
X = pd.Series([1, 2, 3],
              [pd.Timestamp('2017-01-01 08:30:00'),
               pd.Timestamp('2017-01-01 09:30:00'),
               pd.Timestamp('2017-01-01 10:30:00')],
              )
FEATURE = pd.Series([0, 4, 2],
                    [pd.Timestamp('2017-01-01 08:00:00'),
                     pd.Timestamp('2017-01-01 09:00:00'),
                     pd.Timestamp('2017-01-01 10:00:00')]
                    )

f, (ax1, ax2) = plt.subplots(2, 1, sharex='all')
X[start:end].plot(ax=ax1)
FEATURE.plot(ax=ax2)
plt.show()

但只显示了FEATURE。如果我把X放在最后,那么只显示X.

1 个答案:

答案 0 :(得分:1)

一种可能的解决方案是使用matplotlib绘制数据,而不是使用pandas plot包装器。

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

start = pd.Timestamp('2017-01-01 08:00:00')
end = pd.Timestamp('2017-01-01 10:00:00')
X = pd.Series([1, 2, 3],
              [pd.Timestamp('2017-01-01 08:30:00'),
               pd.Timestamp('2017-01-01 09:30:00'),
               pd.Timestamp('2017-01-01 10:30:00')],
              )
FEATURE = pd.Series([0, 4, 2],
                    [pd.Timestamp('2017-01-01 08:00:00'),
                     pd.Timestamp('2017-01-01 09:00:00'),
                     pd.Timestamp('2017-01-01 10:00:00')]
                    )

f, (ax1, ax2) = plt.subplots(2, 1, sharex='all') 

ax1.plot(X.index, X.values)
ax2.plot(FEATURE.index, FEATURE.values)

loc = mdates.MinuteLocator([0,30])
ax2.xaxis.set_major_locator(loc)
ax2.xaxis.set_major_formatter(mdates.AutoDateFormatter(loc))
plt.show()

enter image description here