'Plotting two weeks of pandas time series data on single axis in matplotlib
I have two datasets that each cover one week. z1 is from 2022-02-07 to 2022-02-14, and z2 is from 2022-01-31 to 2022-02-07. So they both start on a Monday and end on the next Monday.
I want to plot z1 and z2 so they share the same x and y axes, with xticklabels showing Mon, Tue, etc. How do I do this?
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
z1 = pd.DataFrame(data={'datetime': pd.date_range(start='2022-02-07',end='2022-02-14',freq='1H'), 'data1': np.random.randint(5,40,size=337)})
z1 = z1.set_index('datetime')
z1['day'] = z1.index.day_name()
z2 = pd.DataFrame(data={'datetime': pd.date_range(start='2022-01-31',end='2022-02-07',freq='1H'), 'data2': np.random.randint(22,31,size=337)})
z2 = z2.set_index('datetime')
z2['day'] = z2.index.day_name()
plt.figure(figsize=(14,6))
ax = plt.subplot(111)
ax2 = ax.twinx()
z1.plot(ax=ax, label='this week', lw=2, color='b', x_compat=True)
z2.plot(ax=ax2, label='last week', lw=2, color='r', x_compat=True)
# ax.plot(z1['day'], z1['data1'], label='this week', lw=2, color='b')
# ax2.plot(z2['day'], z2['data2'], label='last week', lw=2, color='r')
ax.xaxis.set_major_locator(mdates.DayLocator())
xfmt = mdates.DateFormatter('%a')
ax.xaxis.set_major_formatter(xfmt)
ax.tick_params(axis="x", rotation=0)
ax.legend()
ax2.legend()
plt.show()
but I want this:
Solution 1:[1]
I don't think it is possible to make a single graph for each of the pandas plots since they have different indices. Using matplotlib, the x-axis should be continuous data using the number of data points. After creating the graph, set_xticks to 24 tick points where the day of the week changes. set_xticklabels to use the day of the week of either data frame and use it as a tick label for each of the 24 ticks.
fig, ax = plt.subplots(figsize=(14,6))
ax = plt.subplot(111)
ax2 = ax.twinx()
ax.plot(np.arange(169), z1['data1'], label='this week', lw=2, color='b')
ax2.plot(np.arange(169), z2['data2'], label='last week', lw=2, color='r')
ax.set_xticks(np.arange(0,169,24))
ax.set_xticklabels(z1.day[::24])
ax.tick_params(axis="x", rotation=0)
fig.legend(bbox_to_anchor=(0.12, 0.12, 0.1, 0.1))
plt.show()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | r-beginners |



