Search code examples
rdateggplot2axis-labels

R x-axis milliseconds to Date labels


so I have a set of data containing the timestamp in milliseconds for each entry. Example data:

"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"

I now want to use the numeric value for the calculations / plotting, but for the visualization itself, I want an interval which shows the date as timestamp (e.g. 14-03-2021 14:00)

currently what i have is:

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

And it looks like this:

enter image description here

So instead of 1.61e+12 etc I need e.g. 14-03-2021 14:00 (not the correct convertion, just as an example)

I also dont really know, why there is already a scale on the x-axis.

Thanks in advance


Solution

  • Convert to posixCT, and then format the x-axis using scale_x_datetime-properties

    sample data used

    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)
    

    code

    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 ) )
    

    output

    enter image description here