R time_trans与POSIXct类的对象一起使用 [英] R time_trans works with objects of class POSIXct

查看:204
本文介绍了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 works with objects of class POSIXct only

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天全站免登陆