Hi:
There are a few things going on here:
1. Look at the class of your date variable; I suspect yours is factor,
perhaps character. You probably want it to be of class Date.
2. The NA rows don't matter for plotting purposes because ggplot2 will
fail to plot points there. You'll get a warning about rows removed
that contain missing values.
Here's one approach to the problem:
DF <- read.table(header = TRUE, stringsAsFactors = FALSE, text = "
year month day temp precip date
2008 1 1 -10 0.0 2008-01-01
2008 1 2 5 NA 2008-01-02
2008 1 3 2 0.1 2008-01-03
2008 1 4 1 0.2 2008-01-04
2008 1 5 2 0.1 2008-01-05
2008 1 6 -3 0.2 2008-01-06
2008 1 7 -8 NA 2008-01-07")
str(DF) # Note the class of date
# In the above, date is of class "character", so the following works
# to convert it to a Date object:
# (uncomment the next line if date is of class "character")
# DF$date <- as.Date(DF$date)
# If yours is of class factor, you need to coerce it to character first,
# then Date: (uncomment if your date is of class "factor")
# DF$date <- as.Date(as.character(DF$date))
str(DF) # Check that the conversion went correctly
# Plot without extending the date axis
# ggplot2 'knows' that date is of class "Date"
# and plots the x-axis accordingly
library(ggplot2)
ggplot(data=DF,aes(x=date, y=precip))+
geom_point(color = "red")+
labs(x = 'Time', y = 'Precipitation')
# Extend the date axis to the end of 2010
ggplot(data=DF,aes(x=date, y=precip))+
geom_point(color = "red")+
labs(x = 'Time', y = 'Precipitation') +
scale_x_date(limits = c(as.Date("2008-01-01"),as.Date("2010-12-31")))
# Ditto, but add the squish argument
ggplot(data=DF,aes(x=date, y=precip))+
geom_point(color = "red")+
labs(x = 'Time', y = 'Precipitation') +
scale_x_date(limits = c(as.Date("2008-01-01"),as.Date("2010-12-31")),
oob=squish)
As with anything in R, you need to understand the types of objects
with which you are dealing. One of the reasons you were getting error
messages is because you were trying to pass character strings as
limits, as in
xlim('2008-01-01','2010-12-31')
If you're trying to define a date range, the two dates need to be
converted to Date objects in concert with scale_x_date(), per my last
two examples above.
When I plot either of the last two graphs, the R evaluator returns the
following warning:
Warning message:
Removed 2 rows containing missing values (geom_point).
These correspond to the two rows in your input data frame that have NA
precip values.
HTH,
Dennis