ggplot2用日期注释方面错误

时间:2019-03-12 15:28:35

标签: r ggplot2

我正在尝试将标签添加到facet_grid图中。我想获得以下结果:

enter image description here

以下是用于创建数据框和图的可复制代码。数据框annotation_text正在存储构面变量与标签值的映射:

myDF <- data.frame(
  some_data = c(3.32, 3.34, 3.41, 3.45, 3.42, 3.44, 3.51, 3.55, 3.32, 3.34, 3.41, 3.45, 3.36, 3.41, 3.50, 3.54, 3.32, 3.34, 3.41, 3.45, 3.32, 3.44, 3.51, 3.42),
  date = as.Date(rep(c('2018-01-01', '2018-02-01', '2018-03-01', '2018-04-01'), 6)),
  segment = rep(c('segment1', 'segment2', 'segment3'), each = 4, n = 2),
  series = rep(c('series1', 'series2'), each = 12))

annotation_text <- data.frame(
  segment = c('segment1', 'segment2', 'segment3'), 
  label = c('label1', 'label2', 'label3'))

library(ggplot2)
p <- ggplot(myDF, aes(x = date, y = some_data, fill = series)) +
  geom_line() +
  geom_point(size = 2, shape = 21) +
  facet_grid(. ~ segment) +
  ylim(0, 5)

我正在尝试使用以下标签添加标签

p + geom_text(
  data = annotation_text, mapping = aes(x = -Inf, y = -Inf, label = label, fill = NULL, inherit.aes = FALSE, parse = FALSE), hjust = -0.3, vjust = -1)

但这将返回以下错误:

  

错误:输入无效:date_trans仅适用于Date类的对象

感谢对此错误的任何帮助。

1 个答案:

答案 0 :(得分:3)

x刻度是日期的基础数字值(以自1970年1月1日起经过的天数为单位),注释中的x值必须为Date类。该错误与ggplot有关,该问题与在date中寻找annotation_text列而不在其上放置标签的位置有关,或者与其他带有Date类值并在{ {1}}。

一种选择是在geom_text()数据框中提供日期值,以便ggplot知道将标签放置在何处。可以通过针对每个annotation_textmyDF过滤到最早的date(假设您希望将标签放置在该x位置)并将其加入segment来完成。我们在下面的annotation_text内即时进行此操作。

geom_text()下面的代码中是一个“代词”,通过它我们可以访问原始.调用中提供的myDF数据帧。 ggplot()左对齐标签,hjust=0硬编码y位置。

y=0.1

enter image description here

一些其他选项和示例将有望阐明发生了什么错误或正确:

将x位置硬编码为library(tidyverse) # To make both ggplot2 and the dplyr pipe available p + geom_text(data = . %>% arrange(date) %>% group_by(segment) %>% slice(1) %>% left_join(annotation_text), aes(label = label), y=0.1, hjust=0) 中的最小日期。还需要将myDF列添加到series或ggplot会引发错误。请注意,这在这里可行,因为标签的x位置在每个构面中都相同。如果我们希望标签在每个构面中位于不同的x位置,则需要在每个面板中提供所需的日期位置。前一种方法是按annotation_text分组,然后在segment的每个级别中选择最低的日期:

segment

与上述相同,但是p + geom_text(data = annotation_text %>% mutate(series=NA), aes(label = label), y=0.1, x=min(myDF$date), hjust=0) 避免了将inherit.aes=FALSE列添加到series的情况:

annotation_text

p + geom_text(data = annotation_text, aes(label = label), y=0.1, x=min(myDF$date), hjust=0, inherit.aes=FALSE) 添加最小日期(具有相同的列名annotation_text),以便ggplot知道标签的位置:

date

下一个失败,因为我们已经将p + geom_text(data = annotation_text %>% mutate(series=NA, date=min(myDF$date)), aes(label = label), y=0.1, hjust=0) 转换为数字,所以它是错误的类:

date

p + geom_text(data = annotation_text %>% mutate(series=NA, date=as.numeric(min(myDF$date))), aes(label = label), y=0.1, hjust=0) 中提供日期列,但现在需要在es中提供一个新名称(annotation_text),以便ggplot知道从哪里获取x值:

new.date