r - 带有 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 轴上的时间尺度不再是时间,数据点出现在图表的中间。
谢谢你的帮助!
解决方案
您所看到的是 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)
但单点不:
sub <- coords[1,]
month <- sub$month
time <- strptime(sub$format_time, format = "%l:%M:%S %p")
plot(month, time)
所以我们通过指定xlim
andylim
参数来修复它。在这种情况下,由于我推断它意味着一年的月份 (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
形式工作......不知道为什么会这样,但这并没有减损情节的实用性.
推荐阅读
- python - 如何使用 Python 搜索和下载文件(不提及文件的 URL)?
- c# - 运行 Scaffold-DbContext 时出现超时错误
- python - 基准测试python(命令行)
- php - 如何拆分数组值,按第一个子字符串分组,并组合第二个子字符串值?
- firebase - firebase数据库读写权限被拒绝
- javascript - 如何在javascript中将八位字节流保存为zip?
- php - 从 php 表单发布到 CSV 文件时没有调用 DateTime
- python - scrapy - 如何使用正则表达式检索变量值
- apache-spark - 从驱动程序运行多个 spark-submit 实例
- microsoft-graph-api - 无法从 Excel OData 访问 MS Graph