【问题标题】:R: In ggplot, how to add multiple text labels on the y-axis for each of multiple dates on the x-axisR:在ggplot中,如何在y轴上为x轴上的多个日期中的每一个添加多个文本标签
【发布时间】:2012-07-15 22:30:45
【问题描述】:

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

这或多或少根据需要工作,但我想知道是否有更好的方法来接近它,如本图表所示(参见下面的代码)我为 120、140 和 3 个 y 轴值中的每一个都有一个列160. 真实数据有更多级别,所以我最终会调用 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)

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-08
      • 1970-01-01
      • 1970-01-01
      • 2018-05-09
      • 2015-02-23
      • 2012-04-26
      相关资源
      最近更新 更多