首页 > 解决方案 > 如何让 ggplot 从特定月份开始 x 轴

问题描述

我想绘制一个从 11 月开始但延续到下一年的赛季的足球比赛进球数图表。所以我想让 x 轴转到 11 月、12 月、1 月等。

这是我必须使用一些玩具数据的地方

library(tidyverse)
library(lubridate)
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))

df %>% 
  mutate(month=month(date,label = TRUE)) %>% 
  group_by(month) %>% 
  summarize(totGoals=sum(goals)) %>% 
  ggplot(aes(month,totGoals)) +
  geom_bar(stat = "identity")

在此处输入图像描述

理想情况下,我想使用 purrr 包来解决这个问题,但我无法掌握 fct_reorder 和 fct_relevel。“月”是一个有序因子

TIA

标签: rggplot2tidyverselubridatepurrr

解决方案


我们可以将month列转换为因子并设置以 开头的级别Novmonth.abb是带有月份缩写的内置 R 对象。

df %>% 
  mutate(month=month(date,label = TRUE)) %>% 
  group_by(month) %>% 
  summarize(totGoals=sum(goals)) %>% 
  mutate(month = factor(month, levels = c(month.abb[11:12], month.abb[1:10]))) %>%
  ggplot(aes(month,totGoals)) +
  geom_bar(stat = "identity") 

在此处输入图像描述


推荐阅读