简体   繁体   English

如何绘制角度在 0-360 度之间的线条

[英]How to plot lines with angle between 0-360 degree

I want to plot a time-angle series in xy coordinates.我想在 xy 坐标中绘制一个时间角度序列。 when the difference between two neighbors is less than 180, they will be lined directly.当两个邻居之间的差值小于180时,它们将直接排成一行。 Otherwise, one will be lined to 360 and another will be lined to 0 with the same time, it means the path crossed the 0/360 point.否则,一个会被划到 360,另一个会被划到 0,这意味着路径穿过了 0/360 点。 What I known is to calculate the two interpolating points first, and plot two segments, is there some smart direct way to do that?我所知道的是先计算两个插值点,然后绘制两个线段,是否有一些聪明的直接方法可以做到这一点?

library(ggplot2)
data<-data.frame(time=c(1,2,3,4),angle=c(200,100,320,20))
#ggplot()+geom_line(data,aes(time,angle))
#three lines codes is expected,but now it is->
ymax=360
ymin=0
ythd=(ymax-ymin)/2 #180
j=1 #left end point number
n=nrow(data)# rignt end point number
aid=data[1,] #aids line from end point to border
gg=ggplot()
for(i in 1:(n-1)){
  delta=data[i+1,2]-data[i,2]
  #divide groups
  if(abs(delta)>ythd){
    gg=gg+geom_line(data=data[j:i,],aes(time,angle))
    j=i+1
    fst=data[i,2]
    stp=data[j,1]-data[i,1]
    aid[1,]=data[i,]
    #interpolating points
    if(delta>0){
      rto=fst/(360-(delta))
      aid[2:3,1]=data[i,1]+rto*stp
      aid[2,2]=ymin
      aid[3,2]=ymax
    }else{
      rto=(360-fst)/(360+delta)
      aid[2:3,1]=data[i,1]+rto*stp
      aid[2,2]=ymax
      aid[3,2]=ymin
    }
    aid[4,]=data[j,]
    #aids line
    gg=gg+geom_line(data=aid[1:2,],aes(time,angle))   
    gg=gg+geom_line(data=aid[3:4,],aes(time,angle))   
  }

}
#the last group
gg=gg+geom_line(data=data[j:n,], aes(time,angle))
gg

Expected output:预期输出: 在此处输入图片说明

This was a fun exercise.这是一个有趣的练习。 Here's what I came up with.这是我想出的。 I only tested on this one dataset so it may need some tweaking.我只在这一个数据集上进行了测试,因此可能需要进行一些调整。

library(tidyverse)
data<-data.frame(t1=c(1,2,3,4),a1=c(200,100,300,20))

data <- data %>%
  arrange(t1) %>%
  mutate(t2 = c(data$t1[-1], 0)) %>%
  mutate(a2 = c(data$a1[-1], 0)) %>%
  mutate(grp = 0)


get_split <- function(t1, t2, a1, a2) {
  # TEST: t1=1;t2=2;a1=10;a2=355
  if((a2 - a1) > 180) {
    return(a1/(a1 + 360 - a2)*(t2 - t1) + t1)
  } else {
    return(NA)
  }
}

data <- rbind(
  data[,c('t1', 'a1', 'grp')],
  data.frame(t1 = mapply(get_split, data$t1, data$t2, data$a1, data$a2),
             a1 = 0,
             grp = 0),
  data.frame(t1 = mapply(get_split, data$t1, data$t2, data$a1, data$a2),
             a1 = 360,
             grp = 1)
)

data <- data[!is.na(data$t1),] %>%
  arrange(t1)

data$grp <- cumsum(data$grp)

ggplot(data) +
  geom_line(aes(x = t1, y = a1, group = grp))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM