Kev W.
Kev W.

Reputation: 169

Changing line type / width for each time series with autoplot and ggplot

I am trying to create one plot to include two time-series:

library(zoo)
library(tseries)
library(ggplot2)
library(ggfortify)

ts1 <- ts(c(1,2,3,4))
ts2 <- ts(c(1.1, 2.1, 3.1, 4.1))
autoplot(ts.union(ts1, ts2), facets = FALSE) +
scale_color_manual(breaks = c("ts1", "ts2"), labels = c("Actual", "Forecasted"), values=c("black", "red"))

After changing the legend titles and colors for each series I want to modify the line width and type, also by series, but calling scale_linetype_manual does not seem to change the plot by a bit. How should I proceed?

Upvotes: 2

Views: 5428

Answers (1)

markus
markus

Reputation: 26373

You need to add the respective aesthetics to your plot before you can change them. For this you need to know the name of the variable that autoplot uses for aesthetic mapping: see the name of the colour scale.

The data frame that is used for plotting looks like this

#  Index plot_group value
#1     1        ts1   1.0
#2     2        ts1   2.0
#3     3        ts1   3.0
#4     4        ts1   4.0
#5     1        ts2   1.1
#6     2        ts2   2.1
#7     3        ts2   3.1
#8     4        ts2   4.1

autoplot creates the column plot_group for you and in order to distinguish the two time series, it maps (only) the colour to it. Hence you could call scale_color_manual.

You can use this variable to map another aesthetics to it, for example size and linetype.

autoplot(ts.union(ts1, ts2), facets = FALSE) +
 scale_color_manual(labels = c("Actual", "Forecasted"),
                    values=c("black", "red")) +
 aes(linetype = plot_group,
     size = plot_group) +
 scale_linetype_manual(labels = c("Actual", "Forecasted"),
                       values = c(1, 2)) +
 scale_size_manual(labels = c("Actual", "Forecasted"),
                   values = c(1, 2))

enter image description here

data

p <- autoplot(ts.union(ts1, ts2), facets = FALSE)
p$data

Upvotes: 4

Related Questions