在GGPLOT2添加文本层面的情节与X轴日期(Add text to a faceted plot

2019-06-26 06:16发布

我是新来GGPLOT2和我一直很高兴,但我有一件事情的难度。

我已经绘制了一些时间序列跨越的一年。 X轴是从类的变量衍生的Date 。 我已经刻面的情节让我有独立的y轴在第7列的时间序列。 这个图形的意义就在于每个方面的相关性与顶部面比较。

我想这样做的最后一件事是在每个面的右上角添加文字(每个面和第一之间的估计Pearson相关)的情节。

这已经被证明是非常困难的,因为geom_text()要求x和文本的每一位y坐标。 如何指定坐标时的X轴为日期,Y轴是每个面有什么不同? 下面是一些示例数据和代码,我到目前为止这样你就可以复制我到目前为止有:

library(ggplot2)

date <- rep(as.Date(1:365,origin='2011-1-1'),7)
location <- factor(rep(1:7,365))
product <- rep(letters[1:7], each=365)
value <- c(sample(1:10, size=365, replace=T),sample(1:3, size=365, replace=T),
           sample(10:100, size=365, replace=T), sample(1:50, size=365, replace=T),
           sample(1:20, size=365, replace=T),sample(50:100, size=365, replace=T),
           sample(1:100, size=365, replace=T))
dat<-data.frame(date,location,product,value)

qplot(date, value, data=dat, geom="line", color=location, group=location, 
      main='Time Series Comparison', xlab='Month (2011)',ylab='Value') + 
        facet_grid(product ~ ., scale = "free_y")

Answer 1:

这不是最整洁的代码,但我认为这是有点像你以后:

library(plyr)

corr_dat<-ddply(dat, .(product), summarise, value=value)
corr.df<-unstack(corr_dat, value~product)

corr_plot <- data.frame(date=max(dat$date),
                        label=paste0("rho==",round(cor(corr.df)[,1], 2)), 
                        ddply(dat, .(product), summarise, 
                          value=(min(value)+max(value))/2))

ggplot(dat, aes(x=date, y=value, color=location, group=location)) + 
  geom_line()+
  facet_grid(product ~ ., scale = "free_y")+
  geom_text(data=corr_plot, aes(x=date, y=value, label=label), 
            colour="black", inherit.aes=FALSE, parse=TRUE)



文章来源: Add text to a faceted plot in ggplot2 with dates on X axis