0

I am using matplotlib to plot a dataframe.

However, I cannot work out how to plot the x-axis correctly as dates, when the x-axis is the df.index dates.

The output below x-axis dates are wrong.

import pandas as pd
import matplotlib.pyplot as plt

dttm = ["2021-01-01", "2021-01-02", "2021-01-03"]
dttm = pd.to_datetime(dttm)
data = [10, 20, 30]

DF = pd.DataFrame()
DF['value'] = data
DF = DF.set_index(dttm)

print(DF)

plt.plot(DF)
plt.gcf().autofmt_xdate()
plt.show()

df printed:

            value
2021-01-01     10
2021-01-02     20
2021-01-03     30

enter image description here

Sylv99
  • 151
  • 8

1 Answers1

1

I don't really know why, but if you juste don't convert the dates to datetime objects, it is working just fine :

I would say that matplotlib has already something to convert dates and doing it twice might ruin it, but that's purely a speculation.

Odhian
  • 351
  • 5
  • 14
  • The example I gave is a cut down version of my code. The dataframe has it's index as dates (datetime64), hence putting "DF = DF.set_index(dttm)" in my code – Sylv99 Oct 04 '21 at 16:15
  • Then lets say your dates are in a column named "date", you can just do : **df["date_str"] = df["date"].astype(str)** and then just do **plt.plot(df["date_str"], df["value"])** – Odhian Oct 04 '21 at 17:01
  • Thanks for that :) – Sylv99 Oct 04 '21 at 18:33
  • 1
    **[Don't Post Screenshots](https://meta.stackoverflow.com/questions/303812/)**. Answer should be posted as [formatted text](https://stackoverflow.com/help/formatting), and only plot images are okay. Also, this is not a good strategy, and is only feasible because the sample has only 3 x-axis ticks. – Trenton McKinney Oct 04 '21 at 18:52