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

如何设置ggplot的X轴从指定月份(11月)开始并跨年显示?

Hey there! The key issue here is that when you use month(date, label = TRUE), the resulting month labels are ordered chronologically from January to December by default. To get your desired Nov → Dec → Jan sequence, we just need to explicitly set the factor levels for the month variable to match your preferred order.

Here's the full working code that calculates total monthly goals and plots them in the correct order:

library(tidyverse)
library(lubridate)

# Your original match data
df <- data.frame(
  date = as.Date(c("2017-11-01","2017-11-15", "2017-12-01","2017-12-15", "2018-01-01","2018-01-15")),
  goals = c(3,2,0,1,3,5)
)

# Process data to get monthly totals with custom month order
df_monthly <- df %>%
  # Convert month to a factor with explicitly defined levels
  mutate(month = factor(month(date, label = TRUE), levels = c("Nov", "Dec", "Jan"))) %>%
  group_by(month) %>%
  summarise(total_goals = sum(goals, na.rm = TRUE)) %>%
  drop_na(month) # Remove any unused months if present

# Create the final chart
ggplot(df_monthly, aes(x = month, y = total_goals)) +
  geom_col(fill = "#1E90FF") + # Shorthand for geom_bar(stat="identity")
  labs(
    title = "Monthly Football Goals (Nov-Jan Season)",
    x = "Month",
    y = "Total Goals Scored"
  ) +
  theme_minimal()

Quick breakdown of the important bits:

  • Custom Factor Order: By wrapping the month label output in factor(..., levels = c("Nov", "Dec", "Jan")), we override R's default Jan-Dec sorting and enforce your desired sequence.
  • Safe Summarization: Adding na.rm = TRUE to the sum calculation ensures missing goal values won't break your totals.
  • Clean Plotting: geom_col is ideal for pre-summarized data, and the minimal theme keeps the focus on the goal counts.

This will produce a bar chart where the X-axis strictly follows your requested Nov → Dec → Jan order, showing the total goals for each month of the cross-year season.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 08:27:56