1

I have two dataframes here. What I want to do is to plot these two dataframes on the same set of axes.

dict1 = {'Date': ['2022-12-02', '2022-12-16', '2023-01-15'], 'Impressions': [20, 21, 19]}
dict2 = {'Date': ['2022-08-02', '2022-09-16', '2023-02-20'], 'Impressions': [18, 51, 48]}

df1 = pd.DataFrame(dict1)
df2 = pd.DataFrame(dict2)

what I have done is this:

fig, ax = plt.subplots()
ax2 = ax.twinx()

df1.plot(x="Date", y="Impressions", ax=ax)
df2.plot(x="Date", y="Impressions", ax=ax2, ls="--")

plt.show()

This did not give the results I want, as the solid line graph starts on the same date as the broken line, i.e 2022-08-02 instead of 2022-12-02 and ends on the 2023-02-20 instead of 2023-02-15. How can I fix this?

This is the graph I get:

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Dushu
  • 31
  • 4
  • As already pointed out by @mozway, convert the `'Date'` column to a `datetime[ns] Dtype`. However, the correct way to use the API with [`pandas.DataFrame.plot`](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.plot.html) is `ax = df1.plot(x="Date", y="Impressions")` and `df2.plot(x="Date", y="Impressions", secondary_y=True, ls="--", ax=ax)` [code and plot](https://i.stack.imgur.com/jLbIG.png) – Trenton McKinney May 12 '23 at 18:59

1 Answers1

2

Make your dates datetime with to_datetime, else your strings will just be used as [0, 1, 2, …] on the X-axis ignoring their meaning as date:

df1['Date'] = pd.to_datetime(df1['Date'])
df2['Date'] = pd.to_datetime(df2['Date'])

fig, ax = plt.subplots()
ax2 = ax.twinx()

df1.plot(x="Date", y="Impressions", ax=ax)
df2.plot(x="Date", y="Impressions", ax=ax2, ls="--")

plt.show()

Output:

enter image description here

mozway
  • 194,879
  • 13
  • 39
  • 75