我只是想绘制一个小型 27 点数据集,其中 X 轴为日期 R 格式的日期 (CommonDate),y 轴为连续变量。
尽管日期变量采用日期格式,甚至在注释掉使用scale_x_date()的部分后,我还是收到此错误。我根据这个特定错误的一些答案尝试了多种调试方法,但没有成功。
样本数据集:我从 27 点数据集中抽取了 12 点数据集
> example
Brand Period X2014_2013 X2015_2014 CommonDate Year
6 B 2014-06-01 -9.168405 -19.508786 2000-05-31 2014
11 B 2014-11-01 33.747651 0.000000 2000-10-31 2014
19 B 2014-07-01 50.199601 0.000000 2000-06-30 2014
20 B 2014-08-01 69.084423 0.000000 2000-07-31 2014
22 B 2014-10-01 130.377668 0.000000 2000-09-30 2014
3 B 2014-03-01 29.807692 9.856387 2000-02-29 2014
NA <NA> <NA> NA NA <NA> NA
NA.1 <NA> <NA> NA NA <NA> NA
2 B 2014-02-01 21.843116 -13.037997 2000-02-01 2014
16 B 2014-04-01 601.443299 43.298060 2000-03-31 2014
5 B 2014-05-01 15.477101 -23.492664 2000-04-30 2014
23 B 2014-11-01 126.591315 0.000000 2000-10-31 2014
Month
6 6
11 11
19 7
20 8
22 10
3 3
NA NA
NA.1 NA
2 2
16 4
5 5
23 11
这是我正在运行的代码。此处您可以使用 data = example
data = perc_change_YOY_abs
newb_brand_abs_perc_YOY_2015 =
ggplot(data = perc_change_YOY_abs, aes(x = CommonDate, y = X2015_2014, colour = Brand))+
geom_point()+
geom_line()+
geom_text(aes(label = paste(round(X2015_2014,0), "%"), hjust = 0, vjust = 1), size = 4)+
scale_x_date(breaks = date_breaks("months"),labels = date_format("%b"))+
scale_y_continuous(breaks = pretty_breaks(n = 8))+
theme_bw()+
xlab(" ")+
ylab("%Change 2015 vs. 2014")+
annotate("text", x = 4, y = 25, label = "Some text")
plot(newb_brand_abs_perc_YOY_2015)
session 信息:
> sessionInfo()
R version 3.2.0 (2015-04-16)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1
locale:
[1] LC_COLLATE=English_United States.1252
[2] LC_CTYPE=English_United States.1252
[3] LC_MONETARY=English_United States.1252
[4] LC_NUMERIC=C
[5] LC_TIME=English_United States.1252
attached base packages:
[1] grid stats graphics grDevices utils datasets
[7] methods base
other attached packages:
[1] lubridate_1.3.3 reshape2_1.4.1 plyr_1.8.3
[4] gridExtra_0.9.1 scales_0.2.5 lattice_0.20-31
[7] ggplot2_1.0.1
loaded via a namespace (and not attached):
[1] Rcpp_0.11.6 digest_0.6.8 MASS_7.3-40
[4] gtable_0.1.2 magrittr_1.5 stringi_0.5-4
[7] proto_0.3-10 tools_3.2.0 stringr_1.0.0
[10] munsell_0.4.2 colorspace_1.2-6 memoise_0.2.1
最佳答案
因此,您可以使用 geom_text(),而不是使用 ggplot 中的 annotate() 函数。
您首先必须使用标签制作数据表或框架
x <- as.Date(c('2000-07-24'))
y <- c(30)
labs <- 'Some Text'
labelData <- data.table(x = x, y = y, labs = labs)
它应该看起来像这样
x y labs
1: 2000-07-24 30 Some Text
注意 x 列是日期类型。
然后在你的 ggplot 调用中,替换
annotate("text", x = 4, y = 25, label = "Some text")
与
geom_text(aes(x, y, label = labs, group = NULL), data = labelData)
这应该能解决你的问题!我认为 annotate 在将 x 坐标解释为 Date 类型时遇到困难,但 geom_text 可以很好地处理它。
关于r - 尽管变量的格式合适,但仍出现以下错误 : Error: Invalid input: date_trans works with objects of class Date only,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31249842/