Search code examples
pythonpandasmatplotlibdatetimexticks

How to display the x-axis in as yy.m only for the first month of the year and the rest as m


This is my example code and output.

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

# Create a DataFrame with a date column and another column with the data you want to plot
data = {'Date': ['2023-01-01', '2023-02-01', '2023-03-01', '2024-01-01', '2024-02-01'],
        'Value': [10, 15, 13, 18, 20]}
df = pd.DataFrame(data)

# Convert the 'Date' column to datetime
df['Date'] = pd.to_datetime(df['Date'])

# Create a Matplotlib plot using the date data for the x-axis and the 'Value' column for the y-axis data
plt.plot(df['Date'], df['Value'], marker='o', linestyle='-')
plt.xlabel('Date')
plt.ylabel('Y-axis Label')
plt.title('Your Plot Title')


enter image description here

Can I set x-axis format like belows? I want to display yy.m only on the first day of each year and m for the rest.

enter image description here


Solution

    • You must set the major and minor formatters and locators.
    data = {'Date': ['2023-01-01', '2023-02-01', '2023-03-01', '2024-01-01', '2024-02-01'],
            'Value': [10, 15, 13, 18, 20]}
    df = pd.DataFrame(data)
    
    # Convert the 'Date' column to datetime.date which results in the labels being centered under the xticks
    df['Date'] = pd.to_datetime(df['Date']).dt.date
    
    # plot the data
    ax = df.plot(x='Date', rot=0, figsize=(7, 5))
    
    # format the major ticks
    ax.xaxis.set_major_formatter(mdates.DateFormatter('%y.%m'))
    ax.xaxis.set_major_locator(mdates.MonthLocator(bymonth=1, interval=1))
    
    # format the minor ticks
    ax.xaxis.set_minor_locator(mdates.MonthLocator())
    ax.xaxis.set_minor_formatter(mdates.DateFormatter("%m"))
    

    enter image description here

    ax.xaxis.set_minor_locator(mdates.MonthLocator(bymonth=[3, 5, 7, 9, 11]))
    

    enter image description here