简体   繁体   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

I am making a very wide chart that, when output as a PNG file, takes up several thousand pixels in the x-axis; 我正在制作一个非常宽的图表,当输出为PNG文件时,在x轴上占用几千个像素; there is about 20 years of daily data. 有大约20年的每日数据。 (This may or may not be regarded as good practise, but it is for my own use, not for publication.) Because the chart is so wide, the y-axis disappears from view as you scroll through the chart. (这可能会或可能不会被视为良好做法,但它仅供我自己使用,而不是用于发布。)因为图表太宽,所以当您滚动图表时,y轴会从视图中消失。 Accordingly I want to add labels to the plot at 2-yearly intervals to show the values on the y-axis. 因此,我想以2年的间隔向图中添加标签,以显示y轴上的值。 The resulting chart looks like the one below, except that in the interests of keeping it compact I have used only 30 days of fake data and put labels roughly every 10th day: 得到的图表看起来像下面的图表,除了为了保持紧凑,我只使用了30天的假数据并且大约每隔10天放置标签:

在gggplot2中用y轴值标记图

This works more or less as required, but I wonder if there is some better way of approaching it as in this chart (see code below) I have a column for each of the 3 y-axis values of 120, 140 and 160. The real data has many more levels, so I would end up with 15 calls to geom_text to put everything on the plot area. 这可以根据需要或多或少地工作,但我想知道是否有更好的方法来接近它,如在此图表中(参见下面的代码)我有一个列,分别为120,140和160的3个y轴值。真实数据有更多级别,所以我最终会调用15次geom_text来将所有内容放在绘图区域。

Q. Is there a simpler way to splat all 20-odd dates, with 15 labels per date, on to the chart at once? 问:是否有更简单的方法将所有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 likes data to be in long format, so melt() ing your text into long format lets you make a single call to geom_text() : GGPLOT2喜欢的数据是在长格式,所以melt()荷兰国际集团的文本长格式让你做一个调用geom_text()

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

Then your plotting command becomes: 然后你的绘图命令变成:

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