繁体   English   中英

使用学年作为x轴标签

[英]Using Academic Years as x-Axis Labels

考虑以下示例:

library(ggplot2)
library(dplyr)
set.seed(30)

data <- data.frame(group = factor(1:11), 
                   year = c(rep("2013-2014", times = 11), 
                            rep("2014-2015", times = 11), 
                            rep("2015-2016", times = 11), 
                            rep("2016-2017", times = 11)), 
                   value = runif(44),
                   stringsAsFactors = FALSE)

data$plot_year <- as.Date(paste0("01/01/", substr(data$year, start = 1, stop = 4)), 
                     format = "%m/%d/%Y")

ggplot(data, aes(x = plot_year, y = value, color = group)) +
  geom_point() + 
  geom_line(linetype = "dotted") + 
  geom_line(data= data %>% 
                  filter(as.numeric(substr(plot_year, start = 1, stop = 4)) < 2015), 
            aes(x = plot_year, y = value, color = group)) + 
  theme_bw()

在此处输入图片说明

正如我们可以看到上面, 2013在x轴对应于2013-20142014对应于2014-2015 ,等等。

我如何才能使用这些轴标签-即2013-20142014-2015 ,等等-来代替目前的x轴的标签? 我在网上找到的每个解决方案都说过以某种形式使用as.Date() ,但这是学年,而不是固定日期。

您可以将学年直接用作图的x值。 只要year是字符或有序因子,就可以使用比较运算符(如<= )进行子集设置(如果year是非有序因子,则不能使用子集)。 作为字符变量,顺序将是字母顺序。 我更喜欢有序的因子,以便可以指定顺序:

data$year = factor(data$year, levels=sort(unique(data$year)), ordered=TRUE)

ggplot(data, aes(x = year, y = value, color = group, group=group)) +
  geom_point() + 
  geom_line(linetype = "dotted") + 
  geom_line(data= data %>% filter(year <= "2014-2015")) + 
  theme_bw()

在此处输入图片说明

尽管我更喜欢使用year的顺序进行子集设置,但是您也可以明确指定要包含的年份:

ggplot(data, aes(x = year, y = value, color = group, group=group)) +
  geom_point() + 
  geom_line(linetype = "dotted") + 
  geom_line(data= data %>% filter(year %in% c("2013-2014","2014-2015"))) + 
  theme_bw()

您可以将日期转换为数字,然后使用带有breakslabels参数的scale_x_continuous

library(ggplot2)
library(lubridate)

# calculate the breaks as numeric corresponding to the dates
br <- as.numeric(as.Date(c("2013-01-01", "2014-01-01", "2015-01-01", "2016-01-01")))
# calculate the labels at each break
lb <- c("2013-2014", "2014-2015", "2015-2016", "2016-2017")

ggplot(data, aes(x = as.numeric(plot_year), y = value, color = group)) +
          geom_point() + 
          geom_line(linetype = "dotted") + 
          geom_line(data= data %>% filter(year(plot_year) < 2015), 
                aes(x = as.numeric(plot_year), y = value, color = group)) + 
          theme_bw() + 
          scale_x_continuous(breaks = br, labels = lb) + xlab("year")

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM