Plotting dates on the X-axis with Python\'s Matplotlib

Using Pandas, we can create a dataframe and set datetime values as the index. Matplotlib's gcf().autofmt_xdate() automatically formats date labels on the X-axis for better readability.

Steps to Plot Dates on X-axis

  • Create a list of date strings and convert them to datetime using pd.to_datetime()

  • Prepare your data values (e.g., [1, 2, 3])

  • Create a DataFrame and assign the data to a column

  • Set the DataFrame index using the datetime values

  • Plot the DataFrame using plt.plot()

  • Format the X-axis dates using plt.gcf().autofmt_xdate()

  • Display the plot with plt.show()

Example

import pandas as pd
import matplotlib.pyplot as plt

# Create date strings and convert to datetime
date_time = ["2021-01-01", "2021-01-02", "2021-01-03"]
date_time = pd.to_datetime(date_time)
data = [1, 2, 3]

# Create DataFrame with datetime index
df = pd.DataFrame()
df['value'] = data
df = df.set_index(date_time)

# Plot the data
plt.plot(df)
plt.gcf().autofmt_xdate()  # Format X-axis dates
plt.title('Time Series Plot with Formatted Dates')
plt.ylabel('Values')
plt.show()

Alternative Approach

You can also create the DataFrame directly with a datetime index ?

import pandas as pd
import matplotlib.pyplot as plt

# Create DataFrame directly with datetime index
dates = pd.to_datetime(["2021-01-01", "2021-01-02", "2021-01-03"])
df = pd.DataFrame({'value': [1, 2, 3]}, index=dates)

# Plot with formatted dates
plt.figure(figsize=(8, 5))
plt.plot(df.index, df['value'], marker='o')
plt.gcf().autofmt_xdate()
plt.title('Time Series Data')
plt.ylabel('Values')
plt.grid(True, alpha=0.3)
plt.show()

How It Works

The gcf().autofmt_xdate() function automatically:

  • Rotates date labels to prevent overlap

  • Adjusts the spacing between labels

  • Formats dates in a readable format

  • Aligns labels properly on the X-axis

Conclusion

Use pd.to_datetime() to convert date strings and set them as DataFrame index. The gcf().autofmt_xdate() function ensures proper formatting of date labels on the X-axis for clear visualization.

Updated on: 2026-03-25T18:03:02+05:30

34K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements