'Pandas: Why df.plot() not show line plots when the x axis is a datetime with millisecond precision?
I am trying to use pandas df.plot() to plot two lines on the same axes from two different dataframes. I want the x-axis to be datetimes. However there seems to be an issue when the datetimes are stored to different precisions in each dataframe. In the example below, df1 has datetimes to second precision, while df2 has datetime to millisecond precision. When I try to plot df2 after df1, the line for df2 does not plot.
I'm using pandas version 1.3.5.
periods = 10
dateRange = [dt.datetime(2022, 4, 12, 9, 20, i) for i in range(periods)]
df1 = pd.DataFrame({'timestamp': dateRange, 'data': np.cumsum(np.random.randn(periods))})
periods2 = int(periods / 2)
dateRange2 = [dt.datetime(2022, 4, 12, 9, 20, 2*i, 300) for i in range(periods2)]
df2 = pd.DataFrame({'timestamp': dateRange2, 'data': np.cumsum(np.random.randn(periods2))})
fig, ax = plt.subplots()
# this does not work
df1.plot(ax=ax, x='timestamp', y='data', label='df1')
df2.plot(ax=ax, x='timestamp', y='data', label='df2')
# this does work
# ax.plot(df['timestamp'], df['data'])
# ax.plot(df2['timestamp'], df2['data'])

Does anyone know how/why this is happening? And how I can prevent this? When doing this in practice, I typically would not know the precisions of the datetimes before plotting.
A few additional notes:
- If I make both datetimes the same precision, both lines plot fine.
- Both datetime columns have the same dtype (
datetime64[ns]). - If I use matplotlib's
ax.plot()to plot the lines, they both appear fine. So I think the issue if with pandasdf.plot().
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
