【问题标题】:Cannot convert a time variable to plot it on ggplot无法转换时间变量以在 ggplot 上绘制它
【发布时间】:2014-11-14 14:04:25
【问题描述】:

我在 Gnu R 中处理时间变量时遇到了两个问题!

首先,我无法使用 as.Posixltas.Date 从因子(或字符)重新编码时间数据(可下载 here)而不会出现错误消息像这样:

字符串不是标准的明确格式

然后我尝试使用以下方法隐藏我的时间数据:

dates <- strptime(time, "%Y-%m-%j")

这只给了我:

不适用

其次,我想(不得不)转换我的时间数据的原因是我想用 ggplot2 绘制它并调整我的 scale_x_continuous (如here 所述)以便它只写我每 50 年(即 1250-01-01、1300-01-01 等)在 x 轴上,否则 x 轴太忙(见下图)。

这是我使用的代码:

library(ggplot2)
library(scales)
library(reshape)
df <- read.csv(file="https://dl.dropboxusercontent.com/u/109495328/time.csv")
attach(df)
dates <- as.character(time)
population <- factor(Number_Humans)
ggplot(df, aes(x = dates, y = population)) + geom_line(aes(group=1), colour="#000099") + theme(axis.text.x=element_text(angle=90)) + xlab("Time in Years (A.D.)")

【问题讨论】:

  • “1250-02-46”是什么日期? 2 月的天数很少超过 29 天。另外,不要使用attach
  • 不建议使用attach? 46 是这种情况下是一年中的第 46 天。这不是我做的,而是我使用的程序。这对 R 来说真的是个问题吗?
  • 你的意思是,如果你通过 R 一些东西,你告诉它“46”是“作为十进制数的月份中的日期 (01–31)”,它实际上不是月份中的日期, R会感到困惑吗?令人震惊的是,是的。您需要 %j,即“十进制数 (001–366) 中的日期”。
  • 呵呵;您正在使用 %j。如果我运行它,gist.github.com/Ironholds/12097162d25dc935960e 是输出。你不会这样吗?
  • 您的时间戳似乎具有三个引用级别。这些引号是否包含在值中?

标签: r ggplot2 strptime


【解决方案1】:

需要把日期列中的引号去掉,然后才能转换成日期格式:

df <- read.csv(file="https://dl.dropboxusercontent.com/u/109495328/time.csv")
df$time <- gsub('\"', "", as.character(df$time), fixed=TRUE)
df$time <- as.Date(df$time, "%Y-%m-%j")


ggplot(df, aes(x = time, y = Number_Humans)) + 
     geom_line(colour="#000099") + 
     theme(axis.text.x=element_text(angle=90)) + 
     xlab("Time in Years (A.D.)") 

【讨论】:

  • 另外,aes(group=1) 是多余的。
  • 嗯,当我删除它时,我得到:geom_path: Each group consist of only one observation. Do you need to adjust the group aesthetic?;不知道是不是有什么问题,也不知道那条竖线是从哪里来的..
  • 您不应将 data.frame 的所有列都转换为字符。使用df$time &lt;- gsub('\"', "", as.character(df$time), fixed=TRUE)
  • 如果您使用as.POSIXctstrptime,您应该始终明确指定时区。在这里使用as.Date 就足够了,它有一个format 参数。例如,df$time &lt;- as.Date(df$time, format="%Y-%m-%j").
  • @TilHund the group=1 我在这里解释的事情:stackoverflow.com/questions/10357768/…
猜你喜欢
  • 2019-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-17
  • 1970-01-01
  • 1970-01-01
  • 2012-11-30
  • 2020-07-01
相关资源
最近更新 更多