在散点图中将箭头线段添加到散点图中

时间:2018-12-05 01:19:52

标签: r plotly arrows

我有XY个数据,我想使用R的{​​{1}} plotly在散点图中绘制。 对于某些点,我有箭头,它们由X和Y的起点和终点坐标定义,我也想绘制它们。

以下是数据:

package

使用set.seed(1) df <- data.frame(x=rnorm(100),y=rnorm(100), arrow.x.start=NA,arrow.y.start=NA, arrow.x.end=NA,arrow.y.end=NA) arrow.idx <- sample(100,20,replace = F) df$arrow.x.start[arrow.idx] <- df$x[arrow.idx] df$arrow.x.end[arrow.idx] <- df$arrow.x.start[arrow.idx]+runif(length(arrow.idx),-0.5,0.5) df$arrow.y.start[arrow.idx] <- df$y[arrow.idx] df$arrow.y.end[arrow.idx] <- df$arrow.y.start[arrow.idx]+runif(length(arrow.idx),-0.5,0.5) 可通过以下方式实现:

ggplot2

哪个给: enter image description here

library(ggplot2) ggplot(df,aes(x=x,y=y))+geom_point()+theme_minimal()+ geom_segment(aes(x=arrow.x.start,y=arrow.y.start,xend=arrow.x.end,yend=arrow.y.end),arrow=arrow()) 中,将绘制点:

plotly

所以我试图弄清楚如何添加箭头。

plotly::plot_ly(marker=list(size=5,color="black"),type='scatter',mode="markers",x=df$x,y=df$y,showlegend=F) %>% plotly::layout(xaxis=list(title="x",zeroline=F,showticklabels=F,showgrid=F,showgrid=F),yaxis=list(title="y",zeroline=F,showticklabels=F,showgrid=F,showgrid=F)) 具有add_segmentsxxendy参数,并添加以下内容:

yend

似乎在行尾添加了一个点:

enter image description here

我在其文档中找不到要在行尾添加箭头的参数。

有什么主意吗?

1 个答案:

答案 0 :(得分:1)

您可以使用注释

plot_ly(df) %>%
  add_markers(~x, ~y) %>%
  add_annotations( x = ~arrow.x.end,
                   y = ~arrow.y.end,
                   xref = "x", yref = "y",
                   axref = "x", ayref = "y",
                   text = "",
                   showarrow = T,
                   ax = ~arrow.x.start,
                   ay = ~arrow.y.start)

enter image description here

相关问题