【发布时间】:2018-12-05 01:19:51
【问题描述】:
我有XY 数据,我想使用R 的plotly package 在散点图中绘制。
对于某些点,我有箭头,由它们的 X 和 Y 开始和结束坐标定义,我也想绘制它们。
以下是数据:
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 可以通过以下方式实现:
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_segments 具有 x、xend、y 和 yend 参数并添加:
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)) %>%
plotly::add_segments(x=df$arrow.x.start,xend=df$arrow.x.end,y=df$arrow.y.start,yend=df$arrow.y.end,line=list(color="blue"))
好像在行尾加了一个点:
我在其文档中找不到将在行尾添加箭头的参数。
有什么想法吗?
【问题讨论】:
-
似乎忽略了
df$xend和df$yend参数,只是将带有箭头的行添加到df$x和df$y。