0

I am trying to switch from plot to ggplot2 and experience some real trouble. Below, I have attached a very simplified version of some code for the plot I would like to obtain:

x <- seq(1, 20, by=1)
y <- seq(1,40, by=2)


date <- seq(as.Date("2000/1/1"), as.Date("2001/8/1"), by = "month")
# I create a data frame with the date and TWO time series
datframe <- data.frame(date,x,y)

I then would like to plot both series, x and y, with the date on the x axis. I would like the first series displayed with red dotted lines and the second series with a black line, as well as obtaining a legend. This is my ggplot2 code I used so far:

ggplot() + geom_line(data = datframe, aes(x=date, y=datframe$x,group="x"), linetype="dotted", color="red") + 

geom_line(data = datframe, aes(x=datframe$date, y=datframe$y, linetype="y"),color = "black")

Well, the problem is that I only have one legend entry and I do not know how to change it. I would really appreciate some hints, I already spent a long time on a simple graph and could not figure it out. I think for you advanced users it might be obvious, sorry for the beginner question but I thank you a lot in advance for any help.

elio rico
  • 71
  • 1
  • 10

2 Answers2

1

I would recommend tidying your data set first (changing it from wide to long) and then using scale_linetype|color_manual:

library(tidyverse)
datframe.tidy <- gather(datframe, metric, value, -date)

my_legend_title <- c("Legend Title")

ggplot(datframe.tidy, aes(x = date, y = value, color = metric)) +
  geom_line(aes(linetype = metric)) +
  scale_linetype_manual(my_legend_title, values = c("dotted", "solid")) +
  scale_color_manual(my_legend_title, values = c("red", "black")) +
  labs(title = "My Plot Title",
       subtitle = "Subtitle",
       x = "x-axis title",
       y = "y-axis title"

Plot

Alternatively, you can use I() in the aesthetic calls in conjunction with scale_color_manual, but this feels a bit more "hacky":

ggplot(datframe, aes(x = date)) +
  geom_line(aes(y = x, color = I("red")), linetype = "dotted") +
  geom_line(aes(y = y, color = I("black")), linetype = "solid") +
  labs(color = "My Legend Title") +
  scale_color_manual(values = c("black", "red"))
JasonAizkalns
  • 20,243
  • 8
  • 57
  • 116
  • Thanks a thousand times @JasonAizkalns , I understand now how you structured it. This will help me a lot! – elio rico Apr 03 '18 at 06:21
1

ggplot works best with "tidy" dataframes

# make a tidy frame (date, variable, value)
library(reshape2)
datframe_tidy <- melt(datframe, id.vars = "date")

# plot
ggplot(datframe_tidy, aes(x = date, y = value, 
                          color = variable, linetype = variable)) +
  geom_line() +
  theme(legend.position = "bottom")

enter image description here

Andrew Lavers
  • 4,328
  • 1
  • 12
  • 19