0

I am new to R. I am not sure why the order of legend is not ordered as expected.

ggplot() +   
  scale_color_manual(values = c("#D55E00","#009E73","#E69F00", "#0072B2")) +
  geom_line(aes(y = linedataOne, x = timeSeries, colour = 'One'), data = linedataMulti) + 
  geom_line(aes(y = linedataTwo, x = timeSeries, colour = 'Two'), data = linedataMulti) + 
  geom_line(aes(y = linedataThree, x = timeSeries, colour = 'Three'), data = linedataMulti) + 
  geom_line(aes(y = linedataFour, x = timeSeries, colour = 'Four and more'), data = linedataMulti) + 
  labs(title = "Hourly Electricity Usage", x = "Hours in the day", y = "Kw/h", caption = "Data: Smart Meter Data")+ 
  labs(colour = "Number of People")

Plot shown Here

I want the 'One' to be first then 'Two, 'three', etc. But, it is ordered by alphabetical order. Is there a way to order it by the sequence I added the line?

Dave2e
  • 22,192
  • 18
  • 42
  • 50
kevin
  • 419
  • 1
  • 3
  • 11
  • 1
    Can you post sample data? Please edit **the question** with the output of `dput(linedataMulti)`. Or, if it is too big with the output of `dput(head(linedataMulti, 20))`. – Rui Barradas Sep 21 '19 at 14:19

1 Answers1

3

These type of ggplot problems are almost always solved by reformatting the data from wide to long. A give away is the need to call the same geom repeatedly, in this case geom_line.

Then, to have the legend properly ordered, set the group as a factor with the right levels and the accompanying labels order.

library(tidyverse)
library(ggplot2)

flevs <- c("linedataOne", "linedataTwo", "linedataThree", "linedataFour")
flabs <- c("One", "Two", "Three", "Four and more")

linedataMulti %>%
  gather(group, value, -timeSeries) %>%
  mutate(group = factor(group, levels = flevs, labels = flabs)) %>%
  ggplot(aes(timeSeries, value, colour = group)) +
  geom_line() +
  scale_color_manual(values = c("#D55E00","#009E73","#E69F00", "#0072B2")) +
  labs(title = "Hourly Electricity Usage", 
       x = "Hours in the day", 
       y = "Kw/h", 
       caption = "Data: Smart Meter Data",
       colour = "Number of People")

enter image description here

Data creation code.

set.seed(2019)
linedataMulti <- replicate(4, cumsum(rnorm(20)))
linedataMulti <- as.data.frame(linedataMulti)
linedataMulti$timeSeries <- 1:20

names(linedataMulti) <- c("linedataOne", "linedataTwo",
                          "linedataThree", "linedataFour",
                          "timeSeries")
Rui Barradas
  • 70,273
  • 8
  • 34
  • 66