Skip to content
Prev 678 / 885 Next

Graph Two Series over Time

A few more suggestions and an update to my ggplot2 plot.

  1) I recommend using SPACES in your code to make things more readable.
  2) Coding things with COLOR isn?t really very useful.  This is an additional variable and should be coded as such.
  3) I don?t really know what detected means, but I?ve coded it as a logical variable.  You could use a factor or character vector instead.
  4) You have used inconsistent date formatting which (without my edits) will cause some years to be 0005 and others to be 2005.  (This will be immediately clear when the plot spans 2000 years ? that?s how I detected the problem.)

Here?s what my first draft would look like:


### Put data into a data frame -- avoid loose vectors
library(dplyr); library(lubridate); require(tidyr) 
library(ggplot2)

# recreate your data in a data frame
MyData <- data_frame(
  Well1 = c(0.005,0.005,0.004,0.006,0.004,0.009,0.017,0.045,0.05,0.07,0.12,0.10,NA,0.20,0.25),
  Well2 = c(0.10,0.12,0.125,0.107,0.099,0.11,0.13,0.109,NA,0.10,0.115,0.14,0.17,NA,0.11),
  dateString = c("2Jan05","7April05","17July05","24Oct05","7Jan06","30March06","28Jun06",
                 "2Oct06","17Oct06","15Jan07","10April07","9July07","5Oct07","29Oct07","30Dec07"),
  date = dmy(dateString)
)

# put the data into "long" format
MyData2 <- 
  MyData %>%
  gather(location, concentration, Well1, Well2) %>%
  mutate(detected = TRUE)

# hand-code your colored values (should be double checked for accuracy)

MyData2$detected[c(1, 2, 5, 15 + 1, 15 + 5, 15 + 10)] <- FALSE

# Create plot using ggplot2

ggplot( data = MyData2 %>% filter(!is.na(concentration)), 
        aes(x = date, y = concentration, colour = location)) +
  geom_line(alpha = 0.8) +
  geom_point( aes(shape = detected, group = location), size = 3, alpha = 0.8) +
  scale_shape_manual(values = c(1, 16)) + 
  theme_minimal()