0

Found on S.O. the following solution to plot multiple data frames:

ax = df1.plot()

df2.plot(ax=ax)

But what if I only want to plot where they overlap?

Say that df1 index are timestamps that spans 24 hour and df2 index also are timestamps that spans 12 hours within the 24 hours of df1 (but not exactly the same as df1).

If I only want to plot the 12 hours that both data frames covers. What's the easies way to do this?

Community
  • 1
  • 1
Norfeldt
  • 8,272
  • 23
  • 96
  • 152

3 Answers3

2

A general answer to a general question:

You have three options:

  1. Filter both DataFrames prior to plotting, such that they contain the same time interval.
  2. Use the xlim keyword from the pandas plotting function.
  3. Plot both dataframes and set the axes limits later on (ax.set_xlim())
Community
  • 1
  • 1
ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
1

There are multiple ways to achieve this. The code snippet below shows two such ways as an example.

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())

enter image description here

lanery
  • 5,222
  • 3
  • 29
  • 43
1

To plot only the portion of df1 whose index lies within the index range of df2, you could do something like this:

ax = df1.loc[df2.index.min():df2.index.max()].plot()

There may be other ways to do it, but that's the one that occurs to me first.

Good luck!

Alex L
  • 1,114
  • 8
  • 11