【问题标题】:Velocity plot in ggplotggplot中的速度图
【发布时间】:2021-11-20 02:49:00
【问题描述】:

我想创建一个速度时间序列图,类似于之前在此线程中提出的问题:Stick Plot for wind speed and direction data in ggplot

我尝试使用我的数据进行绘图,但出现错误提示

“错误:输入无效:date_trans 与 Date 类的对象一起使用 只有。”

谁能帮我解决这个问题?我对 R 编程很陌生,所以它真的对我有很大帮助。这是我的脚本:

Speed <-c(24,23,23,24,26,27,27,27,26,24)
Dir <- c(108,105,103,100,97,96,97,99,101,103)
Date <-c(2016-08-01,2016-08-02,2016-08-3,2016-08-4,2016-08-5,2016-08-6,2016-09-7,2016-09-8,2016-09-9,2016-09-10)

DF <-data.frame(Speed,Dir,Date)
DF$Date <- as.Date(1,as.Date(DF$Date,origin = "2016-08-04"))

ggplot(DF) +
  geom_segment(aes(x = Date,
                   y = 0,
                   xend = Date + lubridate::dhours(Speed * 1 * -cos((90-Dir) / 360 * 2 * pi)),
                   yend = Speed * 1 * -sin((90-Dir) / 360 * 2 * pi),
                   col = factor(Date)
  ),
  arrow = arrow(length = unit(0.5, "cm")) ) +
  geom_point(aes(Date, 0), size = 1) +
  scale_x_date(labels = date_format('%b'), breaks = date_breaks('1 month'))+
  coord_fixed(3600) +
  theme(legend.position = "none")+
  geom_rect(aes(xmin = as.Date("016-08-04", "%Y-%m-%d"), 
                xmax = as.Date("2016-09-18",  "%Y-%m-%d"),ymin = -Inf,ymax = Inf))

【问题讨论】:

  • 你的约会日期真的是这样吗?因为x &lt;-2016-08-01 只返回 2007。这只是数字的减法。你的意思是把它们放在引号里吗?喜欢Date &lt;- c("2016-08-01", "2016-08-02", ...)

标签: r ggplot2 time-series


【解决方案1】:

就像@MrFlick 所说,您首先需要在日期前后加上引号。但是您发布的错误是由于您的线路而发生的

xend = Date + lubridate::dhours(Speed * 1 * -cos((90-Dir) / 360 * 2 * pi))

这使用lubridate 包中的dhours() 函数来为日期添加小时增量。但是,这具有将日期从 R 的内置 Date 类型转换为 lubridate 的 Date 类型的副作用。 ggplotgeom_segment() 仅适用于 R 内置类型的日期。您可以摆脱对dhours() 函数的调用。

我还清理了制作绘图的代码中的其他一些内容,特别是通过coord_fixed(1) 设置固定坐标比,以便忠实地表示您想要的角度。您可能会注意到这些箭头似乎从Dir 指定的方向指向远离。要使箭头指向Dir,您需要删除sincos 之前的负号。

#establish the data
Speed <-c( 24, 23, 23, 24, 26, 27, 27, 27, 26, 24 )
Dir <- c( 108, 105, 103, 100, 97, 96, 97, 99, 101, 103 )
Date <- c('2016-08-01', '2016-08-02', '2016-08-3', '2016-08-4', '2016-08-5', '2016-08-6', '2016-09-7', '2016-09-8', '2016-09-9', '2016-09-10')

DF <- data.frame( Speed, Dir, Date )
DF$Date <- as.Date(1, as.Date(DF$Date, origin = "2016-08-04"))

# make the plot
ggplot(DF) +
    geom_segment(aes(x = Date,
                     y = 0,
                     xend = Date + Speed * 1 * cos( (90-Dir) / 360 * 2 * pi),
                     yend = Speed * 1 * sin( (90-Dir) / 360 * 2 * pi),
                     col = factor(Date)
    ),
    arrow = arrow(length = unit(0.5, "cm")) ) +
    geom_point(aes(Date, 0), size = 1) +
    scale_x_date(labels = date_format('%b'), breaks = date_breaks('1 month')) +
    coord_fixed(1) +
    theme(legend.position = "none")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-14
    • 1970-01-01
    • 2017-11-05
    • 2019-03-24
    • 2015-10-16
    相关资源
    最近更新 更多