gpt4 book ai didi

r - 如何在 ggplot2 中显示曲线的方向?

转载 作者:行者123 更新时间:2023-12-04 12:28:26 24 4
gpt4 key购买 nike

我在 R 中绘制了一个参数化轮廓。我想要做的是沿着曲线添加箭头,以向查看者显示曲线的前进方向。

这是我用来生成曲线的代码:

library(ggplot2)
library(grid)
set.seed(9)
T<-sort(runif(2^12,min=2^-5, max=16))

U<-function(t) exp(4*log(t) - 4*t)*(cos(log(t) + 3*t))
#Re(t^(4+1i)*t)*exp(-(4-3i)*t))
V<-function(t) exp(4*log(t) - 4*t)*(sin(log(t) + 3*t))
#Im(t^(4+1i)*t)*exp(-(4-3i)*t))


X<-sapply(T,U)
Y<-sapply(T,V)

df<-data.frame(X=X,Y=Y)

p<-ggplot(data=df,aes(x = df$X, y = df$Y))

p+theme_bw()+
geom_path(size=1,color='blue',linetype=1) #+
#geom_segment(aes(xend=c(tail(X, n=-1), NA), yend=c(tail(Y, n=-1), NA)),
#arrow=arrow(length=unit(0.2,"cm")),color='blue')
dev.off()

我最后注释掉的部分:

#+
#geom_segment(aes(xend=c(tail(X, n=-1), NA), yend=c(tail(Y, n=-1), NA)),
#arrow=arrow(length=unit(0.2,"cm")),color='blue')

做的事情与我想要的类似,但箭头靠得很近,曲线最终看起来“模糊”而不是定向的。

这是曲线的模糊和非模糊版本:

Fuzzy Curve

enter image description here

谢谢!

最佳答案

如果箭头是 more equally spaced along the curved path 可能会更好看,例如

enter image description here

library(ggplot2)
library(grid)
set.seed(9)
T <- sort(runif(2^12,min=2^-5, max=16))
U <- function(t) exp(4*log(t) - 4*t)*(cos(log(t) + 3*t))
V <- function(t) exp(4*log(t) - 4*t)*(sin(log(t) + 3*t))
drough <- data.frame(x=sapply(T,U), y=sapply(T,V))


p <- ggplot(data = drough, aes(x = x, y = y)) +
geom_path()

## because the parametric curve was generated with uneven spacing
## we can try to resample more evenly along the path
parametric_smoothie <- function(x, y, N=1e2, phase=1, offset=0) {

lengths <- c(0, sqrt(diff(x)^2 + diff(y)^2))
l <- cumsum(lengths)
lmax <- max(l)
newpos <- seq(phase*lmax/N, lmax-phase*lmax/N, length.out = N) + offset*lmax/N
xx <- approx(l, x, newpos)$y
yy <- approx(l, y, newpos)$y
data.frame(x = xx, y = yy)
}

## this is a finer set of points
dfine <- parametric_smoothie(X, Y, 20)

gridExtra::grid.arrange(p + geom_point(data = drough, col="grey"),
p + geom_point(data = dfine, col="grey"), ncol=2)

enter image description here

## now we use this function to create N start points for the arrows
## and another N end points slightly apart to give a sense of direction
relay_arrow <- function(x, y, N=10, phase = 0.8, offset = 1e-2, ...){

start <- parametric_smoothie(x, y, N, phase)
end <- parametric_smoothie(x, y, N, phase, offset)

data.frame(xstart = start$x, xend = end$x,
ystart = start$y, yend = end$y)

}

breaks <- relay_arrow(drough$x, drough$y, N=20)

p + geom_point(data = breaks, aes(xstart, ystart), col="grey98", size=2) +
geom_segment(data = breaks, aes(xstart, ystart, xend = xend, yend = yend),
arrow = arrow(length = unit(0.5, "line")),
col="red", lwd=1)

关于r - 如何在 ggplot2 中显示曲线的方向?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40938416/

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