Hydro
Hydro

Reputation: 1117

Legends with correct color in ggplot?

I want to plot lines individually so that I can control the color and shape of each line. If I specify the colors outside aes(), I would get the right colors, but lose the legend.

Why are the lines not getting the right color when defined inside aes()? I do not want to use gather or pivot_wider.

library(tidyverse)
library(lubridate)

set.seed(1500)

FakeData <- data.frame(Date = seq(as.Date("2020-01-01"), 
                                  to = as.Date("2020-01-31"), 
                                  by = "days"),
                       Level = runif(31, 0, 30), 
                       Flow = runif(31, 1,10),
                       PCP = runif(31, 0,25), 
                       MeanT = runif(31, 1, 30))
ggplot(data = FakeData, aes(x = Date))+
  geom_line(aes(y = Level, col = "black"))+
  geom_line(aes(y = Flow, col = "blue"))+
  geom_line(aes(y = PCP, col = "red"))+
  geom_line(aes(y = MeanT, col = "grey"))

enter image description here

Upvotes: 1

Views: 1010

Answers (1)

Duck
Duck

Reputation: 39595

You can try this:

library(tidyverse)
library(lubridate)

set.seed(1500)

FakeData <- data.frame(Date = seq(as.Date("2020-01-01"), to = as.Date("2020-01-31"), by = "days"),
                       Level = runif(31, 0, 30), Flow = runif(31, 1,10),
                       PCP = runif(31, 0,25), MeanT = runif(31, 1, 30))
#Melt data
Meltdata <- reshape2::melt(FakeData,id.vars='Date')
#Plot
ggplot(data = Meltdata, aes(x = Date,y=value,color=variable,group=variable))+
  geom_line()+
  scale_color_manual(values=c("black","blue","red","grey"))

enter image description here

Upvotes: 3

Related Questions