繁体   English   中英

R:在ggplot中,如何在y轴上为x轴上的每个多个日期添加多个文本标签

[英]R: In ggplot, how to add multiple text labels on the y-axis for each of multiple dates on the x-axis

我正在制作一个非常宽的图表,当输出为PNG文件时,在x轴上占用几千个像素; 有大约20年的每日数据。 (这可能会或可能不会被视为良好做法,但它仅供我自己使用,而不是用于发布。)因为图表太宽,所以当您滚动图表时,y轴会从视图中消失。 因此,我想以2年的间隔向图中添加标签,以显示y轴上的值。 得到的图表看起来像下面的图表,除了为了保持紧凑,我只使用了30天的假数据并且大约每隔10天放置标签:

在gggplot2中用y轴值标记图

这可以根据需要或多或少地工作,但我想知道是否有更好的方法来接近它,如在此图表中(参见下面的代码)我有一个列,分别为120,140和160的3个y轴值。真实数据有更多级别,所以我最终会调用15次geom_text来将所有内容放在绘图区域。

问:是否有更简单的方法将所有20多个日期(每个日期有15个标签)一次性打印到图表上?

require(ggplot2)

set.seed(12345)
mydf <- data.frame(mydate = seq(as.Date('2012-01-01'), as.Date('2012-01-31'), by = 'day'),
                     price = runif(31, min = 100, max = 200))

mytext <- data.frame(mydate = as.Date(c('2012-01-10', '2012-01-20')),
                col1 = c(120, 120), col2 = c(140,140), col3 = c(160,160))

p <- ggplot(data = mydf) +
    geom_line(aes(x = mydf$mydate, y = mydf$price), colour = 'red', size = 0.8) +
    geom_text(data = mytext, aes(x = mydate, y = col1, label = col1), size = 4) +
    geom_text(data = mytext, aes(x = mydate, y = col2, label = col2), size = 4) +
    geom_text(data = mytext, aes(x = mydate, y = col3, label = col3), size = 4)

print(p)

GGPLOT2喜欢的数据是在长格式,所以melt()荷兰国际集团的文本长格式让你做一个调用geom_text()

require(reshape2)
mytext.m <- melt(mytext, id.vars = "mydate")

然后你的绘图命令变成:

ggplot(data = mydf) +
  geom_line(aes(x = mydf$mydate, y = mydf$price), colour = 'red', size = 0.8) +
  geom_text(data = mytext.m, aes(x = mydate, y = value, label = value), size = 4)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM