我如何说服ggplot2 geom_text在时间序列图中标记指定的日期? [英] How can I persuade ggplot2 geom_text to label a specified date in a time series plot?

查看:450
本文介绍了我如何说服ggplot2 geom_text在时间序列图中标记指定的日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用ggplot2绘制时间序列数据的简单线形图。我遇到的一个困难是标记与x轴值相对应的特定点,例如日期。

  library(ggplot2)$ b $ (比例)
日期< - c(2011-09-19,2011-09-20,2011-09-21,
2011-09-22 ,2011-09-23,2011-09-26,2011-09-27)
price <-c(100,110,105,115,120,115,125)
tmp < - data.frame(date (tmp,aes(tmp $ date,tmp $ price))
p < - ggplot p + xlab(Date)
p <-p + ylab(Price)
p <-p + layer(geom =line)
p <-p + opts (title =Simple price plot)
print(p)

我想要什么要做的是添加注释到特定的日期,这可能是最大值或最小值或其他值得注意的地方。到目前为止,我所使用的geom_text的所有排列都未能得到我想要的效果(或实际上任何有用的效果)。关于这个问题有几个问题,但大多数似乎与散点图有关,而不是时间序列;我没有成功地尝试去适应它们。我也花了一些时间与文档,但我的理解仍然有限。任何指针将不胜感激。

解决方案

要添加文本到 ggplot ,使用 geom_text



方法1:为您的 data.frame添加一列标签

  tmp $ note<  -  LETTERS [1:7] 

ggplot(tmp,aes(date,price,label = note))+
geom_line()+
geom_text(vjust = 0,color =red)



方法2:添加特定标签:

  ggplot( tmp,aes(date,price,label = date))+ 
geom_line()+
geom_text(data = tmp [3,],label =Something of note,vjust = 1)


I am using ggplot2 to plot simple line charts of time series data. One difficulty I have run into is labelling specific points corresponding to x-axis values i.e. dates.

library(ggplot2)
library(scales)
date <- c("2011-09-19","2011-09-20","2011-09-21",
    "2011-09-22","2011-09-23","2011-09-26","2011-09-27")
price <- c(100,110,105,115,120,115,125)
tmp <- data.frame(date,price)
tmp$date <- as.Date(tmp$date)
p <- ggplot(tmp,aes(tmp$date,tmp$price))
p <- p + xlab("Date")
p <- p + ylab("Price")
p <- p + layer(geom = "line")
p <- p + opts(title="Simple price plot")
print(p)

What I would like to do is add an annotation to a specific date, which might be a maximum or a minimum value or something else of note. So far all the permutations of geom_text I have used have failed to get the effect I want (or indeed anything useful). There are a few questions on this on SO but most seem related to scatter charts rather than time series; I haven't been successful in trying to adapt them. I have also spent some time with the documentation but my understanding is still limited. Any pointers would be appreciated.

解决方案

To add text to ggplot, use geom_text:

Method 1: Add a column of labels to your data.frame:

tmp$note <- LETTERS[1:7]

ggplot(tmp,aes(date, price, label=note)) +
  geom_line() +
  geom_text(vjust=0, colour="red")

Method 2: Add a specific label:

ggplot(tmp,aes(date, price, label=date)) +
  geom_line() +
  geom_text(data=tmp[3, ], label="Something of note", vjust=1)

这篇关于我如何说服ggplot2 geom_text在时间序列图中标记指定的日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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