簡體   English   中英

當x軸是Date時,RHS上的R ggplot注釋

[英]R ggplot annotation on RHS when x axis is a Date

我試圖在ggplot的右側添加一些文本,其中日期為x軸但我在設置Date對象的annotation_custom xmin和xmax參數時遇到問題。 我將不勝感激為此提供一些幫助。

library(ggplot2)
library(quantmod)
getSymbols("SPY", from="2013-11-01", to=Sys.Date())

SPY = data.frame(SPY)
SPY$Date = as.Date(rownames(SPY))
colnames(SPY)[6] = 'Price'
tail(SPY)

gg1 <- ggplot(data=SPY, aes(x=Date, y=Price)) + geom_line() + theme_bw()
gg1 <- gg1+ theme(plot.margin = unit(c(0.1,6,0.1,0.1), "cm"))
gg1

Text1 = textGrob("xxxxxxxxxxxxxxxxxxxxxxxxxxx")
Text1

ymax1 <- max((SPY)[6])
ymin1 <- min((SPY)[6])
xmin1 <- tail(SPY$Date,1)
xmax1 <- tail(SPY$Date,1)+10

gg1 <- gg1 + annotation_custom(grob = Text1, 
               xmin = xmin1, xmax = xmax1, ymin = ymin1, ymax = ymax1) 
gg1 <- ggplot_gtable(ggplot_build(gg1))
gg1$layout$clip[gg1$layout$name=="panel"] <- "off"
grid.draw(gg1)


Error in Ops.Date((x - from[1]), diff(from)) : 
  / not defined for "Date" objects

Error in UseMethod("grid.draw") : 
  no applicable method for 'grid.draw' applied to an object of class "c('gg', 'ggplot')"

改變線

gg1 + annotation_custom(grob = Text1, 
                        xmin = xmin1, xmax = xmax1, ymin = ymin1, ymax = ymax1) 

gg1 + annotation_custom(grob = Text1,
                        xmin = as.numeric(xmin1), xmax = as.numeric(xmax1),
                        ymin = as.numeric(ymin1), ymax = as.numeric(ymax1))

ggplot2的例子

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM