首页 > 解决方案 > 带有 strptime 的 plot(x,y) 不适用于奇异数据点

问题描述

我正在尝试在 y 轴上使用一天中的时间绘制一个闪亮的散点图。绘制多个点时,y 轴看起来很棒。

样本图

这是代码:

     output$outputPlot <- renderPlot({
        coords <- subset(coords, location == input$cities)
        month <- coords$month
        time <- strptime(coords$format_time, format = "%l:%M:%S %p")
        plot(month, time)
      })

但是当 中只有 1 个数据点时coords,图表在 y 轴上的时间尺度不再是时间,数据点出现在图表的中间。

样地 2

谢谢你的帮助!

标签: rplottimeshiny

解决方案


您所看到的是 R 不知道如何猜测单个点的适当范围。通常,它会将数据范围扩大 4% 的范围(查看?par并寻找'xaxs'),但只有一个点没有任何意义。

所以我们需要告诉它ylim使用什么。(同样,您的 x 轴也需要一些指导。)

假数据:

set.seed(2)
coords <- data.frame(tm = Sys.time() + runif(20, -3e7, 3e7))
coords$month <- as.integer(format(coords$tm, format = "%m"))
coords$format_time <- format(coords$tm, format = "%l:%M:%S %p")
head(coords)
#                    tm month format_time
# 1 2018-10-24 20:15:17    10  8:15:17 PM
# 2 2019-10-19 05:07:04    10  5:07:04 AM
# 3 2019-07-21 14:19:22     7  2:19:22 PM
# 4 2018-10-13 03:44:57    10  3:44:57 AM
# 5 2020-04-03 21:32:22     4  9:32:22 PM
# 6 2020-04-03 15:27:59     4  3:27:59 PM

“正常”情节看起来不错:

month <- coords$month
time <- strptime(coords$format_time, format = "%l:%M:%S %p")
plot(month, time)

很多点,很好的y轴

但单点不:

sub <- coords[1,]
month <- sub$month
time <- strptime(sub$format_time, format = "%l:%M:%S %p")
plot(month, time)

单点,错误的y轴

所以我们通过指定xlimandylim参数来修复它。在这种情况下,由于我推断它意味着一年的月份 (x) 和一天的时间 (y),我可以对它们进行硬编码,但在其他情况下,您可能只想减去/添加一个您拥有的一个数据中的少量:

sub <- coords[1,]
month <- sub$month
time <- strptime(sub$format_time, format = "%l:%M:%S %p")
xlim <- c(1, 12)
ylim <- strptime(c("12:00:00 AM", "11:59:59 PM"), format = "%l:%M:%S %p")
plot(month, time, xlim = xlim, ylim = as.numeric(ylim))

一点,校正轴

你只需要指定ylim回答这个问题,但是xlim=这里不设置,之前的x轴跨越6-14,不好几个月。另外值得注意的是,我不得不ylim为情节强制使用数字,它不能以ylim纯粹的POSIXt形式工作......不知道为什么会这样,但这并没有减损情节的实用性.


推荐阅读