R time_trans 适用于 POSIXct 类的对象 [英] R time_trans works with objects of class POSIXct

查看:15
本文介绍了R time_trans 适用于 POSIXct 类的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有股票价格的数据(数据).股票数据我想可视化它.我首先使用 ggplot R 绘图来可视化该系列.

I have data with stock prices(data). Stock data I would like to visualize it. I first use ggplot R plotting to visualize the series.

    Date      Closed
2010-07-19    0.0808
2010-07-20    0.7547

当我使用下面的代码时

    my_date_format <- function()
{
  function(x)
  {
    m <- format(x,"%b")
    y <- format(x,"%Y")
    ifelse(duplicated(y),m,paste(m,y))
  }
}

ggplot(data, aes(x=Date, z=Closed)) +
  geom_point() +
  scale_x_datetime(breaks = date_breaks("1 month"), labels=my_date_format())

我有一个错误:错误:输入无效:time_trans 仅适用于 POSIXct 类的对象

I had an error: Error: Invalid input: time_trans works with objects of class POSIXct only

当然,我尝试将 Date 更改为 Date 格式,但也没有用.我也试过了

Of course I tried to change Date as a Date format, but it didn't work too. I also tried

    ggplot(data, aes(Date, Closed)) + geom_line() +
  scale_x_date(format = "%Y-%m-%d") + xlab("") + ylab("Closed")

or

ggplot(data,aes(Date,Closed))+geom_line() + scale_x_date(breaks = "1 month",labels=date_format("%b/%y")) +xlab(" ") + ylab("closed")

但它也不起作用.我想要的输出看起来像这样

but it doesn't work too. My desired output looks similary like this

推荐答案

使用参数 date_labels 应该可以正常工作:

This should work fine using the argument date_labels:

library(ggplot2)
library(lubridate)
data <- read.table(text= "
Date      Closed
                   2010-07-19    0.0808
                   2010-07-20    0.7547
                   2010-07-21    0.8547", stringsAsFactors=FALSE, header = TRUE)

data$Date <- ymd(data$Date)
ggplot(data, aes(x=Date, y=Closed)) + 
  geom_line() + scale_x_date(date_labels = "%b-%d-%Y")

关于您的代码,如果您的数据格式为 date(假设它们是),则不能使用 scale_x_datetime.这就是您收到错误的原因:Error: Invalid input: time_trans 仅适用于 POSIXct 类的对象

Regarding you codes, you can't use scale_x_datetime if the format of your data is date (Assuming that they are). That's why you get the error: Error: Invalid input: time_trans works with objects of class POSIXct only

这篇关于R time_trans 适用于 POSIXct 类的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆