我的数据看起来像:
require(ggplot2); require(lubridate); require(data.table); require(dplyr)
Date <- rep(seq.Date(as.Date("2014-01-01"), as.Date("2016-12-31"), by = "days"), 3)
Index <- rep(c(rep(1:365, times = 2), 1:366), 3)
Counts<- sample(1:25, size = length(Index), replace = TRUE)
City <- rep(c("Dallas", "San Antonio", "Houston"), each = length(Index)/3)
df <- data.frame(Date = Date, Index = Index, Counts = Counts, City = City)
df <- df %>% mutate(Year = year(as.Date(Date)))
我使用以下代码绘制数据:
ggplot(df, aes(x = Index, y = Counts, colour = City)) +
geom_line(aes(group = City))+
geom_vline(xintercept = c(31, 59.5, 90, 120, 151, 181, 212, 243, 273, 304, 334))+
facet_grid(Year~.) +
theme(legend.position = "bottom")
我的目标是将x轴标记为 Jan Feb ... Dec 。我试过scale_x_continuous
和scale_x_discrete
但没有用。有什么建议吗?
提前致谢
答案 0 :(得分:1)
如果您使用Date
作为x
变量并使用scale_x_date
,我认为这更容易实现:
df <- df %>% mutate(Year = year(as.Date(Date)),
MonthStart = round_date(Date, unit = "month"))
mid_months <- seq.Date(as.Date("2014-01-15"), as.Date("2016-12-15"), by = "months")
ggplot(df, aes(x = Date, y = Counts, colour = City)) +
geom_line(aes(group = City))+
facet_wrap(~ Year, ncol = 1, scales = "free") +
geom_vline(aes(xintercept = MonthStart), colour = 'black') +
# expand = c(0,0) to ensure scale doesn't extend to additional
# months
scale_x_date(breaks = mid_months, date_labels = "%b", expand = c(0, 0)) +
theme(legend.position = "bottom")
编辑:已更新以添加月中标签
答案 1 :(得分:0)
利用您已经获得的内容的快速选项是将x截取的向量作为中断传递给scale_x_continuous
,并使用month.abb
命名它们:
library(tidyverse)
df <- data_frame(
Date = rep(seq.Date(as.Date("2014-01-01"), as.Date("2016-12-31"), by = "days"), 3),
Index = rep(c(rep(1:365, times = 2), 1:366), 3),
Counts = sample(1:25, size = length(Index), replace = TRUE),
City = rep(c("Dallas", "San Antonio", "Houston"), each = length(Index) / 3),
Year = lubridate::year(Date)
)
month_breaks <- c(31, 59.5, 90, 120, 151, 181, 212, 243, 273, 304, 334)
ggplot(df, aes(x = Index, y = Counts, colour = City)) +
geom_line() +
geom_vline(xintercept = month_breaks) +
scale_x_continuous(breaks = month_breaks, labels = month.abb[-1]) +
facet_grid(Year ~ .) +
theme(legend.position = "bottom")