r - ggplot2 添加指向特定数据点的动态箭头注释,这些数据点与整个图的比例保持比例

标签 r ggplot2 annotations stock arrows

我想创建一个模板,允许我创建股票价格的折线图,并能够添加指向特定日期的箭头。 ggplot2 上的注释功能不允许根据绘图的比例调整大小。有什么解决方法吗?

例如,在这个只有 6 个日期的图中,箭头的大小与图表相匹配:

prices<-c(3,5,28,17,62,10)
prices2<-prices-1
prices3<-prices-11
dates<-seq.Date(from=as.Date("2018-1-1"),to=as.Date("2018-1-6"),"days")

ggplot()+
geom_line(aes(dates,prices))+
annotate(
"segment",
x=dates,
xend=dates,
y=prices3,
yend=prices2,
color="blue",
arrow=arrow(length=unit(0.5,"cm")
            ))

enter image description here

但是,当我将周期增加到 15 个日期时,箭头不按比例缩放,看起来像这样:

enter image description here

最佳答案

我不确定你所说的比例到底是什么意思,它与第一个数字的比例长度基本相同吗?如果是这样,由于箭头的长度由 prices2prices3 控制,您只需计算出它们在第一个数字上按比例占用多少空间,然后计算第二个数字.结合 npc 作为箭头,它应该大致给你你想要的。由于 x 轴的原因,箭头本身并不完美,但我认为它比您之前的更接近。

因此使用您的数据:

# original data
prices<-c(3,5,28,17,62,10)
dates<-seq.Date(from=as.Date("2018-1-1"),to=as.Date("2018-1-6"),"days")

# original plot (with 0.05 npc)
ggplot()+
    geom_line(aes(dates,prices))+
    annotate(
        "segment",
        x=dates,
        xend=dates,
        y=prices-11,
        yend=prices-1,
        color="blue",
        arrow=arrow(length=unit(0.05,"npc")
        ))

enter image description here

# new data
prices2<-c(prices,c(20,250,30,60,40))
dates2 <- seq.Date(from=as.Date("2018-1-1"),to=as.Date("2018-1-11"),"days")

# compute length of arrow
p1 <- abs(min(prices)-11)+max(prices)
fs1<-function(x) { (abs(min(prices2)-x)+max(prices2))*11/p1-x }
y1<-uniroot(fs2,lower=0,upper=100)$root

p2 <- abs(min(prices)-1)+max(prices)
fs2<-function(x) { (abs(min(prices2)-x)+max(prices2))*1/p2-x }
y2<-uniroot(fs1,lower=0,upper=100)$root

# new plot
ggplot()+
geom_line(aes(dates2,prices2))+
annotate(
    "segment",
    x=dates2,
    xend=dates2,
    y=prices2-y1,
    yend=prices2-y2,
    color="blue",
    arrow=arrow(length=unit(0.05,"npc")
    ))

enter image description here

关于r - ggplot2 添加指向特定数据点的动态箭头注释,这些数据点与整个图的比例保持比例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50356585/

相关文章:

r - 使用具有固定参数的 nls 吗?

image - R:将 alpha 值添加到 png-image

r - 离散值到连续尺度

debugging - 列出在 R 中设置了调试标志的函数

删除 ggplot2 中 geom_ribbon 的图例键周围的填充

R - ggplot2 - X 轴标签不会显示

r - 在ggplot中保留不同数量面板的面板大小

java - 帮助注释

java - 有没有办法让 Hibernate 的 hbm2ddl Ant 任务排除特定的表?

java - 我可以快速找到合适的MirrorAnnotation吗?