r - 为 x 轴标签使用时间值
问题描述
我有一些温度和湿度的气候数据以及转换为时间的时间戳%H:%M
。
当使用 ggplot2 进行可视化时,时间会被排序 - 因为第一次测量是在 14:00(下午 2 点)进行的,最后一次测量是在第二天的 10:27(上午 10:27)进行的,所以时间会被排序。
如何防止 ggplot2 对 x 值进行排序?(见情节)
MVE:
library(tidyverse)
df = read_csv('./climate_stats_incl_time.csv')
colnames(df)[1] <- c('sample')
head(df)
tail(df)
ggplot(data=df, mapping=aes(x=time)) +
geom_line(aes(y=temperature, color='red')) +
geom_line(aes(y=humidity, color='blue'))
> head(df)
# A tibble: 6 x 5
sample timestamp temperature humidity time
<dbl> <dbl> <dbl> <dbl> <drtn>
1 0 1581253210. 21.9 47.6 14:00
2 1 1581253275. 21.7 47.8 14:01
3 2 1581253336. 21.7 47.8 14:02
4 3 1581253397. 21.8 47.8 14:03
5 4 1581253457. 21.7 47.8 14:04
6 5 1581253520. 21.8 47.8 14:05
> tail(df)
# A tibble: 6 x 5
sample timestamp temperature humidity time
<dbl> <dbl> <dbl> <dbl> <drtn>
1 1203 1581326567. 19.1 49.8 10:22
2 1204 1581326628. 19.1 49.7 10:23
3 1205 1581326688. 19.1 49.9 10:24
4 1206 1581326749. 19.1 49.9 10:25
5 1207 1581326812. 19.1 49.7 10:26
6 1208 1581326873. 19.1 49.8 10:27
解决方案
将您的时间戳格式化为适当的日期时间(假设原点是 1970 年):
df$date_time <- as.POSIXct(df$timestamp, origin="1970-01-01", tz = "GMT")
然后使用这个新date_time
变量而不是time
绘图
编辑:
我不小心提交了错误的解决方案(我将日期时间重新格式化为日期)。现在解决方案应该适用于您的问题(即它可以生成日期时间!)
推荐阅读
- javascript - 将随机对象的键设置为不同的值
- microservices - 相同请求的定义是什么?
- powershell - Powershell CSV 目录
- css - 将样式组件与从 node_module 导入的 CSS 文件一起使用
- mysql - 如何执行类型严格的 JOIN
- javascript - 向 createElement 添加函数
- json - 使用 sed 从 JSON 响应中获取准确值
- c# - 如何使用 PageFactory 在子类中定义 @findBy 注释?
- azure-service-fabric - 如何修复独立 Service Fabric 群集中的错误 IP 地址
- visual-studio - 使用 Visual Studio 2019 构建但依赖于 MFC140U.dll