Héctor - 1 year ago 108

R Question

I need to make several time-series graphs in the same format as shown in Fig. I'm interested in the format itself.

I will be grateful for your help.

Here a minimal example with simulated data

`set.seed(1234)`

nobs<-50

x<-rnorm(nobs,0,10)

t<-seq(1,nobs)

data<-ts(20+x+t, freq=4, start=c(2004,1))

par(family="serif")

plot(data, lwd=2, col="blue4", ylab="Millions")

title(main="Gráfico 1. Evolución del ...")

legend(2010,10,"GDP", col="blue4",lwd=2)

abline(lm(data~t), lwd=2, col="red") # This does not work

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

I assume that your data is a `ts`

object, as in your example. Here is an approach using `base`

graphics. We start off with a minimal plot, then layer on elements. First, the minimal plot, making sure to leave lots of space at side 1 (i.e. bottom):

```
par(mar = c(8, 4, 4, 2), family = "serif", las = 1)
plot(data,
frame = FALSE,
xaxt = "n",
ylab = "Millones de pesos", xlab = "",
main = "Gráfico 1. Evolución del ...",
col = "darkblue", lwd = 2)
fit <- forecast::tslm(data ~ trend)
lines(fitted(fit), col = "red", lwd = 2)
```

Note that above, we use `forecast::tslm`

to get the time trend for the time series. Now, add the x-axis elements. I use `mtext`

to insert the tick labels:

```
axis(1, at = seq(2003.875, 2015.875, 1), tck = -.2, labels = FALSE)
mtext(rep(c("ener-mar", "abril-jun", "jul-sep", "oct-dic"), l = length(data)),
side = 1, line = 0.25, las = 2,
at = seq(tsp(data)[1], tsp(data)[2], by = 1/tsp(data)[3]),
cex = .6)
mtext(2004:2016, side = 1, line = 3, at = seq(2004.3, 2016.3), cex = .7)
title(xlab = "Trimestres", line = 5, cex.lab = .8)
```

Finish off with the legend:

```
par(xpd = TRUE)
legend(2010, -27, c("PIB", "Tendencia PIB"),
bty = "n",
xjust = .5,
lty = c(1, 1),
col = c("darkblue", "red"),
cex = .7,
horiz = TRUE)
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**