Related time axes (x axis) in matplotlib shape

This is based on the generation of the second x axis, as described in this previous post:

matplotlib: adding second axes () with transparent background?

Below is the code for generating a graph with two X axes, which represent two different time units for the same data: relative time ( rel_time) and absolute time ( abs_time). Although the method described above generates two axes well, the data scales differently between them.

How can I generate a graph with two x-axes that are connected? That is, the data plotted on both axes must be aligned with the other.

Also, is there a way to do this without strict data ( y) twice? As a result, the data must be aligned, so a second graph must be created to create a new axis.

Code below:

# Based on question:
# /questions/475409/matplotlib-adding-second-axes-with-transparent-background
import time
import numpy as np
import matplotlib.pyplot as plt

# Plot Data
rel_time = np.arange(-10.0, 40)  # seconds
abs_time = rel_time + time.time()  # epoch time
y = np.array([1.1, 1.2, 1.2, 1.1, 1.2, 1.1, 1.3, 1.3, 1.2, 1.1, 1.4, 1.7, 
              2.5, 2.6, 3.5, 4, 4.3, 4.8, 5, 4.9, 5.3, 5.2, 5.5, 5.1, 
              5.4, 5.6, 5.1, 6, 6.2, 6.2, 5.5, 6.1, 5.4, 6.3, 6.2, 6.5,
              6.3, 6.1, 6.5, 6.6, 6.1, 6.6, 6.5, 6.4, 6.6, 6.5, 6.2, 6.6,
              6.4, 6.8])  # Arbitrary data

fig = plt.figure()
fig.subplots_adjust(bottom=0.25)  # space on the bottom for second time axis

host = fig.add_subplot(111)  # setup plot

p1 = host.plot(rel_time, y, 'b-')  # plot data vs relative time
host.set_xlabel("Relative Time [sec]")
host.set_ylabel("DATA")

newax = host.twiny()  # create new axis
newax.set_frame_on(True)
newax.patch.set_visible(False)
newax.xaxis.set_ticks_position('bottom')
newax.xaxis.set_label_position('bottom')
newax.spines['bottom'].set_position(('outward', 50))
newax.plot(abs_time, y, 'k-')  # plot data vs relative time
newax.set_xlabel("Absolute Time [Epoch sec]")

plt.show()

generates a time series plot with inconsistent x-axes: Timeseries Plot with mismatched x-axes that display different time units

+3
source share
1 answer

You need to specify limits for your x-axes. If you add these lines, it will do this:

host.set_xlim(rel_time[0],rel_time[-1])
newax.set_xlim(abs_time[0],abs_time[-1])

two curves are constructed:

enter image description here

If you do not want to retrieve data twice, just delete the line newax.plot().

+4
source

All Articles