如何让 ggplot 从特定月份开始绘制 x 轴
How do I get a ggplot to start the x axis from specific month
我想绘制一个从 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。 'month' 是有序因子
TIA
我们可以将 month
列转换为因子并设置水平以 Nov
开头。 month.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")
绘制 YYYY-MM 而不是 MM,这样它将按年排序。
library(tidyverse)
library(lubridate)
df <- data.frame(date = c("2017-11","2017-11",
"2017-12","2017-12",
"2018-01","2018-01"),
goals = c(3,2,0,1,3,5))
df = df %>%
group_by(date) %>%
summarize(totGoals=sum(goals))
plot = ggplot(df, aes(date,totGoals)) +
geom_bar(stat = "identity")
print(plot)
我想绘制一个从 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。 'month' 是有序因子
TIA
我们可以将 month
列转换为因子并设置水平以 Nov
开头。 month.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")
绘制 YYYY-MM 而不是 MM,这样它将按年排序。
library(tidyverse)
library(lubridate)
df <- data.frame(date = c("2017-11","2017-11",
"2017-12","2017-12",
"2018-01","2018-01"),
goals = c(3,2,0,1,3,5))
df = df %>%
group_by(date) %>%
summarize(totGoals=sum(goals))
plot = ggplot(df, aes(date,totGoals)) +
geom_bar(stat = "identity")
print(plot)