【问题标题】:R x-axis milliseconds to Date labelsR x 轴毫秒到日期标签
【发布时间】:2021-06-12 15:50:57
【问题描述】:

所以我有一组数据,其中包含每个条目的时间戳(以毫秒为单位)。 示例数据:

"date","lowest_price","median_price","volume"
"1615219740000","1.61€","1.61€","13.785"
"1615322760000","1.46€","1.51€","12.496"
"1615322760000","1.46€","1.51€","12.496"
"1615322820000","1.46€","1.51€","12.496"
"1615322940000","1.46€","1.51€","12.496"
"1615323540000","1.49€","1.51€","12.496"
"1615324140000","1.49€","1.51€","12.496"
"1615326000000","1.50€","1.45€","12.413"

我现在想使用数值进行计算/绘图,但对于可视化本身,我想要一个将日期显示为时间戳的间隔(例如 14-03-2021 14:00)

目前我拥有的是:

pp <- ggplot(data=breakout_case, aes(x = date, y = lowest_price, group = 1)) +
  geom_line() + 
  theme(axis.text.x = element_text(angle = 90)) +
  labs(title = "Operation Breakout Case Price-chart",
        x = "Date",
        y = "Price"
        )
pp

它看起来像这样:

所以我需要例如而不是 1.61e+12 等14-03-2021 14:00(不是正确的转换,只是举例)

我也不太清楚,为什么x轴上已经有刻度了。

提前致谢

【问题讨论】:

  • 一些示例数据会有所帮助。最简单的可能是在绘图之前将您的时间戳转换为 posixCT.. 然后您可以从 ggplot2-timestamp 轴选项中获得所有灵活性
  • 我添加了一些示例数据。希望能帮助到你。我将尝试将其转换为 posixCT。

标签: r date ggplot2 axis-labels


【解决方案1】:

转换成posixCT,然后用scale_x_datetime-properties格式化x轴

使用的样本数据

mydata <- read.table( text = ' "date","lowest_price","median_price","volume"
                      "1615219740000","1.61€","1.61€","13.785"
                      "1615322760000","1.46€","1.51€","12.496"
                      "1615322760000","1.46€","1.51€","12.496"
                      "1615322820000","1.46€","1.51€","12.496"
                      "1615322940000","1.46€","1.51€","12.496"
                      "1615323540000","1.49€","1.51€","12.496"
                      "1615324140000","1.49€","1.51€","12.496"
                      "1615326000000","1.50€","1.45€","12.413" ', 
                      sep = ",", header = TRUE)

代码

library( tidyverse )
library( scales )
mydata %>%
  dplyr::mutate( timestamp = date %>% 
                   as.numeric %>% #make it numeric
                   `/`(1000) %>%  #divide by 1000
                   as.POSIXct( origin = "1970-01-01" ) ) %>% #set to POSIXct
  ggplot( aes( x = timestamp, y = lowest_price, group = 1 ) ) + 
  geom_line() +
  #set axis properties here
  scale_x_datetime( breaks = "3 hour", 
                    labels = scales::date_format( "%Y-%m-%d %H:%M" ) ) +
  #rotete x-labels
  theme( axis.text.x = element_text( angle = 90, vjust = 0.5 ) )

输出

【讨论】:

    猜你喜欢
    • 2014-10-12
    • 2014-08-20
    • 2011-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-04
    • 2018-11-21
    相关资源
    最近更新 更多