Cannot convert a time variable to plot it on ggplot

1.3k views Asked by At

I have two problems handling my time variable in Gnu R!

Firstly, I cannot recode the time data (downloadable here) from factor (or character) with as.Posixlt or with as.Date without an error message like this:

character string is not in a standard unambiguous format

I have then tried to covert my time data with:

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

which only gives me:

NA

Secondly, the reason why I wanted (had) to convert my time data is that I want to plot it with ggplot2 and adjust my scale_x_continuous (as described here) so that it only writes me every 50 year (i.e. 1250-01-01, 1300-01-01, etc.) in the x-axis, otherwise the x-axis is too busy (see graph below).

enter image description here

This is the code I use:

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.)")
1

There are 1 answers

6
erc On BEST ANSWER

You need to remove the quotation marks in the date column, then you can convert it to date format:

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

enter image description here