用于标记R中ggplot2折线图中的局部极值的函数

时间:2013-11-19 19:00:48

标签: r ggplot2

我正在绘制一个时间序列,我想自动标记特定点,例如最后一点和本地极值,最高点和最低点。

如何在函数中包装它以自动标记关键点。特别是通过添加更多的局部极值。

以下是一个示例数据集:

latest <- structure(list(ReleaseDate = structure(c(1363928400, 1364533200, 
1365138000, 1365742800, 1366347600, 1366952400, 1367557200, 1368162000, 
1368766800, 1369371600, 1369976400, 1370581200, 1371186000, 1371790800, 
1372395600, 1373000400, 1373605200, 1374210000, 1374814800, 1375419600, 
1376024400, 1376629200, 1377234000, 1377838800, 1378443600, 1379048400, 
1379653200, 1380258000, 1380862800, 1381467600, 1382072400, 1382677200, 
1383282000, 1383890400, 1384495200), class = c("POSIXct", "POSIXt"
), tzone = ""), Count = c(1746L, 1748L, 1738L, 1771L, 1758L, 
1754L, 1764L, 1769L, 1769L, 1762L, 1771L, 1765L, 1771L, 1759L, 
1748L, 1757L, 1759L, 1770L, 1776L, 1782L, 1778L, 1791L, 1776L, 
1776L, 1767L, 1768L, 1761L, 1744L, 1756L, 1743L, 1739L, 1738L, 
1742L, 1754L, 1762L)), .Names = c("ReleaseDate", "Count"), row.names = 150:184, class = "data.frame")

enter image description here

library(ggplot2)
libary(ddply)

last <- tail(latest, 1)
high <- subset(latest, Count == max(Count))
mid <- subset(latest[5:20,], Count == min(Count))

ggplot(latest, aes(ReleaseDate, Count)) + geom_line()  + 
  geom_text(data = last, aes(ReleaseDate, Count), label = last$Count, vjust = -1) + 
  geom_text(data = high, aes(ReleaseDate, Count), label = high$Count, vjust = -.1) + 
  geom_text(data = mid, aes(ReleaseDate, Count), label = mid$Count, vjust = 1)

在这里,我尝试手动添加特定点,但如果我想为更长的系列添加10个标签,则不会简洁。

0 个答案:

没有答案