gpt4 book ai didi

r - 在 plotly 中将箭头段添加到散点图

转载 作者:行者123 更新时间:2023-12-04 01:49:55 25 4
gpt4 key购买 nike

我有 XY 数据,我想使用 Rplotly 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())

给出: enter image description here

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_segmentsxxendyyend参数并添加:

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"))

好像是在行尾加了一个点:

enter image description here

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

有什么想法吗?

最佳答案

可以使用注解

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

关于r - 在 plotly 中将箭头段添加到散点图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53623808/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com