SecretBeach
SecretBeach

Reputation: 197

Error in as.Date.numeric(data$Oxygen) for ggplot

I'm kind of new to stack overflow. I have this very large data set with a problem in ggplot, but I've been able to distill it down to this:

data <- data.frame(
+     Date <- sample(c("1993-07-09", "1993-08-16", "1993-09-13", "1993-10-11", "1993-11-08")),
+     Oxygen <- sample(c("15", "15.8", "15.3", "16", "16"))
+ )
data$Oxygen <- as.numeric(as.character(data$Oxygen))
data$Date <- as.Date(data$Date)

ggplot(data = data, aes(x=Date, y=Oxygen)) + 
    geom_point() +
    geom_smooth(method = "loess", se=FALSE) +
    scale_x_continuous(breaks = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12), label = c("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")) +
    theme(axis.text.x=element_text(angle = -360, hjust = 0)) +
    theme(plot.title = element_text(hjust = 0.5)) +
    theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),panel.background = element_blank(), axis.line = element_line(colour = "black"))

After this, I get this error:

Error in as.Date.numeric(value) : 'origin' must be supplied

For various reasons, I had to manually label the x axis. My data set has values for many years and for all months. I don't know how to get around this error, since I need R to recognize that that column are dates.

Any help would be greatly appreciated!

Upvotes: 3

Views: 946

Answers (1)

mischva11
mischva11

Reputation: 2956

Instead of using scale_x_continuous you can use the build in function of ggplot for dates: scale_x_date(). It can be used like following example:

scale_x_date(date_breaks = "1 month", date_minor_breaks = "1 week", date_labels = "%B")

This is a more fitting approach for your intended use.

Credits and further explanation for scale_x_date

Upvotes: 3

Related Questions