You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将图表X轴从年日数字(1-365)改为月份格式?

Convert Day-of-Year X-Axis to Month Labels

Hey there! Converting your X-axis from day-of-year (1-365) to month-based labels is totally doable—let’s break down the most common methods depending on the tool you’re using:

Using Python’s Matplotlib (Most Common for Data Visualization)

First, we’ll map those day-of-year numbers to actual dates, then format the X-axis to show months. We’ll use pandas for date handling since it simplifies leap year logic:

  1. Convert day-of-year to dates

    import pandas as pd
    import matplotlib.pyplot as plt
    import matplotlib.dates as mdates
    
    # Define your target year (use a leap year like 2024 to cover all 366 days)
    target_year = 2024
    day_of_year = range(1, 366)  # Adjust to 365 if using a non-leap year
    
    # Convert day numbers to full dates
    dates = pd.to_datetime(day_of_year, unit='D', origin=f'{target_year}-01-01')
    
  2. Plot with date-based X-axis
    Assume you have corresponding Y-values stored in y_data:

    fig, ax = plt.subplots(figsize=(10, 6))
    ax.plot(dates, y_data)
    
  3. Format X-axis to show months

    # Set major ticks to start of each month
    ax.xaxis.set_major_locator(mdates.MonthLocator())
    # Format ticks to show month abbreviations (use "%B" for full names like "January")
    ax.xaxis.set_major_formatter(mdates.DateFormatter('%b'))
    
    # Rotate labels to prevent overlap (optional but helpful)
    plt.xticks(rotation=45, ha='right')
    
    plt.tight_layout()
    plt.show()
    

Using Excel

If you’re working in Excel, here’s a quick workflow:

  • Add a new column next to your day-of-year data. Use the DATE function to convert day numbers to dates:
    =DATE(2024, 1, A2)  # Replace 2024 with your year, A2 with the cell containing day-of-year
    
  • Right-click your chart → Select Data → Replace the X-axis data range with your new date column.
  • Right-click the X-axis → Format Axis → Under Axis Options, set Units to "Months" and adjust the Label Format to show abbreviations or full month names.

Using R’s ggplot2

For R users, here’s how to do it with ggplot2:

library(ggplot2)
library(lubridate)

# Convert day-of-year to dates
target_year <- 2024
day_of_year <- 1:366
dates <- ymd(paste(target_year, 1, 1)) + days(day_of_year - 1)

# Create dataframe and plot
df <- data.frame(date = dates, y = your_y_data)
ggplot(df, aes(x = date, y = y)) +
  geom_line() +
  scale_x_date(date_breaks = "1 month", date_labels = "%b") +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

内容的提问来源于stack exchange,提问作者Ivanovitch

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:39:55