0
votes

I am new to R, and I am working on graphing data that is spread out over the years 1963-2014. In my data, I have one column for the year (year), another for a month (month), and another for the concentration of magnesium in the water (Mg).

I am trying to make a scatter plot of how magnesium concentration has changed over time, but if I plot years on the x-axis and magnesium on the y, I end up with 12 points (one for each month) stacked on top of each other for every year. My data is called water2, and it produces this graph.

Is there a way to ask R to spread these magnesium points out over the months and the years, essentially using two columns to define 1 x-axis? Alternatively, is there a way to create a new column that will define the years and months in one?

1
paste is a good way to stick two strings together. Alternatively you could use an actual Date class and set the dates to, e.g., the first day of each month. - Gregor Thomas

1 Answers

0
votes
# dummy data  
data <- data.frame(year = rep(1963:2014, each = 12),
                   month = rep(1:12, times = 52),
                   value = cumsum(rnorm(12*52)))


# convert it to a time-series object and plot it :
data.ts <- ts(data$value, start = 1963, frequency = 12)
plot.ts(data.ts, type = "p")


# Or you can ignore the time variables and just make a "index plot" with one variable :
plot(data$value, type = "p", xaxt = "n")
axis(1, at = seq(1, 12*52, by = 12), labels = 1963:2014)


# If you wanna merge year and month and generate a new variable :
data <- within(data, time <- paste(year, month, sep = "-"))
head(data)

  year month       value   time
1 1963     1 -0.56389506 1963-1
2 1963     2  0.60636512 1963-2
3 1963     3  0.04645893 1963-3
4 1963     4 -0.76187300 1963-4
5 1963     5 -1.22781272 1963-5
6 1963     6 -2.33044086 1963-6