将文本添加到 ggplot2 中的多面图,X 轴上带有日期 [英] Add text to a faceted plot in ggplot2 with dates on X axis

查看:18
本文介绍了将文本添加到 ggplot2 中的多面图,X 轴上带有日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 ggplot2 的新手,它很棒,但我在一件事上遇到了困难.

I am new to ggplot2 and it's been wonderful, but I'm having difficulty with one thing.

我已经绘制了许多跨越一年的时间序列.X 轴源自 Date 类的变量.我已经对情节进行了刻面,以便在具有独立 y 轴的列中有 7 个时间序列.该图的重点是比较每个刻面与顶部刻面的相关性.

I have plotted a number of time series that span a year. The X axis is derived from a variable of class Date. I have faceted the plot so that I have 7 time series in a column with independent y axes. The whole point of this graphic is to compare the correlation of each facet with the top facet.

我想做的最后一件事是将文本(每个方面与第一个方面之间的估计 pearson 相关性)添加到每个方面右上角的图中.

The last thing I would like to do is add text (the estimated pearson correlation between each facet and the first) to the plot in the upper right hand corner of each facet.

这被证明是非常困难的,因为 geom_text()需要每个文本位的 x 和 y 坐标.当 X 轴是日期并且 Y 轴对于每个方面都不同时,如何指定坐标?以下是我目前拥有的一些示例数据和代码,因此您可以重现我目前拥有的内容:

This is proving to be extremely difficult because geom_text()requires x and y coordinates for each bit of text. How do I specify coordinates when the X axis is dates and the Y axis is different for each facet? Here's some sample data and the code I have so far so you can reproduce what I have so far:

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")

推荐答案

这不是最简洁的代码,但我认为它有点像你所追求的:

This isn't the neatest code, but I think it's somewhat like what you're after:

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)

这篇关于将文本添加到 ggplot2 中的多面图,X 轴上带有日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆