ggplot2 segment — direction when x-axis is time

半世苍凉 提交于 2019-12-05 18:12:24

Using the suggestions of @eipi10 to calculate the appropriate ratio and multiply by the change in x but not explicitly setting the coordinate limits, here's a solution that correctly displays wind directions of 45 degrees and the length of the segment corresponds to the windspeed.

date <- seq(ymd('2012-04-07'),ymd('2013-03-22'), by = 'day')
windspeed <- rnorm(n = length(date), mean = 5, sd = 1)
dir <- rep((c(0,30,45,60,90)*(pi/180)), times = length(date)/5)

data <- data.frame(date, windspeed, dir)

rat <-as.numeric(interval(min(date), max(date))) / (max(windspeed) - min(windspeed))

data <- data %>%
    mutate(DelY = windspeed * sin(dir)/(2*max(windspeed)),
           DelX  = rat * windspeed * cos(dir)/(2*max(windspeed)))



plt1 <- ggplot(data = data, aes(x = date, y =windspeed))
plt1 + geom_point(color="blue")+
  geom_segment(aes(x= date, y = windspeed, xend = date + DelX,
                   yend=windspeed + DelY),size=.1,color="red") +
  coord_fixed(ratio = rat)

If you are open to an alternative to geom_segment(), then you can use geom_text() with an ANSI (unicode) arrow symbol to get the desired output:

ggplot(data = data, aes(x=date, y=windspeed)) + 
  geom_point() + 
  geom_text(aes(angle=-dir+90), label="→")
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!