Search code examples
rquantmod

chartSeries - how to make the plot x label as original date in dataframe


When I use quantmod::chartSeries to draw chart ,how to make the plot x label format as original in data.frame ? Thank! Below code ,the chart x label is not correce

test_data <- data.frame(mydate=as.Date(c('2013-1-1','2023-1-6','2023-1-20')),
                       open = c(1,7,8),
                       high=c(7,10,9),
                       low= c(1,3,4),
                       close=c(1.5,6,7.5))

quantmod::chartSeries(ts(test_data))

Solution

  • library(quantmod)
    library(xts)
    
    # Create the data.frame
    test_data <- data.frame(mydate = as.Date(c('2013-1-1', '2023-1-6', '2023-1-20')),
                            open = c(1, 7, 8),
                            high = c(7, 10, 9),
                            low = c(1, 3, 4),
                            close = c(1.5, 6, 7.5))
    
    # Convert the data.frame to an xts object
    test_xts <- xts(test_data[, -1], order.by = test_data$mydate)
    
    # Plot the chart
    chartSeries(test_xts, name = "Test Chart")