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

GFauxPas

我有一个要绘制的参数化轮廓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') 

所做的事情与我想要的相似,但是箭头非常靠近并且曲线最终看起来“模糊”而不是有方向。

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

模糊曲线

在此处输入图片说明

谢谢!

浸礼会

如果箭头在弯曲路径上的间距更均匀,则可能看起来更好,例如

在此处输入图片说明

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)

在此处输入图片说明

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章