代码之家  ›  专栏  ›  技术社区  ›  user3685918

如何仅在一年的第一个月将x轴显示为yy.m,其余显示为m[重复]

  •  0
  • user3685918  · 技术社区  · 2 年前

    这是我的示例代码和输出。

    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

    我可以像下面这样设置x轴格式吗? 我想显示 yy.m 仅在每年的第一天 m 其余部分。

    enter image description here

    1 回复  |  直到 2 年前
        1
  •  0
  •   Trenton McKinney    2 年前
    • 您必须设置主要和次要格式化程序。
    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