【问题标题】:Pandas plot ONLY overlap between multiple data frames熊猫图仅在多个数据框之间重叠
【发布时间】:2017-06-16 06:01:14
【问题描述】:
发现于 S.O.绘制多个数据框的以下解决方案:
ax = df1.plot()
df2.plot(ax=ax)
但是如果我只想绘制它们重叠的地方呢?
假设 df1 索引是跨越 24 小时的时间戳,而 df2 索引也是 df1 24 小时内跨越 12 小时的时间戳(但与 df1 不完全相同)。
如果我只想绘制两个数据框涵盖的 12 小时。有什么简单的方法可以做到这一点?
【问题讨论】:
标签:
python
pandas
matplotlib
ipython
jupyter-notebook
【解决方案2】:
有多种方法可以实现这一点。下面的代码sn-p以两种方式为例。
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# Make up time data for 24 hour period and 12 hour period
times1 = pd.date_range('1/30/2016 12:00:00', '1/31/2016 12:00:00', freq='H')
times2 = pd.date_range('1/30/2016 12:00:00', '1/31/2016 00:00:00', freq='H')
# Put time into DataFrame
df1 = pd.DataFrame(np.cumsum(np.random.randn(times1.size)), columns=['24 hrs'],
index=times1)
df2 = pd.DataFrame(np.cumsum(np.random.randn(times2.size)), columns=['12 hrs'],
index=times2)
# Method 1: Filter first dataframe according to second dataframe's time index
fig1, ax1 = plt.subplots()
df1.loc[times2].plot(ax=ax1)
df2.plot(ax=ax1)
# Method 2: Set the x limits of the axis
fig2, ax2 = plt.subplots()
df1.plot(ax=ax2)
df2.plot(ax=ax2)
ax2.set_xlim(times2.min(), times2.max())
【解决方案3】:
要仅绘制 df1 的索引位于 df2 的索引范围内的部分,您可以执行以下操作:
ax = df1.loc[df2.index.min():df2.index.max()].plot()
可能还有其他方法可以做到这一点,但这是我首先想到的方法。
祝你好运!