1

My dataframe consists of daily temperature data for the months June, July and August of the years 2002 - 2017.

date          temperature
2002-06-01    9.882000
2002-06-02    9.698667
2002-06-03    12.941667
...
2017-08-29    13.271125
2017-08-30    16.332750
2017-08-31    20.986000

The dates are in format POSIXct. I´m trying to create a plot that shows only the relevant months per year. I tried ggplot2 with the following code:

ggplot(NULL, aes(x = date, y = temperature)) +
   geom_line(data = tair_summer_night_mean, color = "blue") +
   xlab(label = "Time") +
   ylab(label = "Night time temperature in °C")

This leads to:

enter image description here

Is there a way to tell ggplot not to display the space where I have no data?

erc
  • 10,113
  • 11
  • 57
  • 88
Kai.K
  • 31
  • 1
  • 4

1 Answers1

1

This follows up on camille's suggestion. Plotting your data by facets is probably the most straightforward solution. You can either create a year column in your data as shown in her reference and then group on that or you can compute the grouping variable in gglot as shown below.

library(ggplot2)
#
#  make some test data
#
  tair_summer_night_mean <- data.frame(date=c( seq.Date(as.Date("2002-06-01"), as.Date("2002-08-31"),1), 
                                        seq.Date(as.Date("2003-06-01"), as.Date("2003-08-31"),1), 
                                        seq.Date(as.Date("2004-06-01"), as.Date("2004-08-31"),1)))
  tair_summer_night_mean[,"temperature"] <-  runif(nrow(tair_summer_night_mean), min=9, max=21 )
#
#  make plots faceted by year
# 
  sp <-  ggplot(tair_summer_night_mean, aes(x = date, y = temperature)) +
         geom_line(color = "blue") + 
         xlab(label = "Time") +
         ylab(label = "Night time temperature in °C") +
         facet_wrap( ~ format(date, "%Y"), scales = "free_x")
   plot(sp)

which gives the chart

enter image description here

WaltS
  • 5,410
  • 2
  • 18
  • 24