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

GFa*_*Pas 2 r ggplot2

我有一个参数化的轮廓,我正在绘制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()
Run Code Online (Sandbox Code Playgroud)

我评论的最后一部分:

#+
#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') 
Run Code Online (Sandbox Code Playgroud)

做了类似于我想要的事情,但箭头非常接近,曲线最终看起来"模糊"而不是指向.

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

模糊曲线

在此输入图像描述

谢谢!

bap*_*ste 6

如果箭头沿着弯曲路径更均匀地间隔,则可能看起来更好,例如

在此输入图像描述

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)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

## 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)
Run Code Online (Sandbox Code Playgroud)