Jimmy Lee
Jimmy Lee

Reputation: 117

How to order one legend according to another legend in ggplot2 R?

I have two different datasets but with the same label names. After i plotted both plots, I found that the legends are not in the same order, and the colour were different too. Wonder what I should do to make sure they are consistent?

enter image description here

Thank you very much!!

Upvotes: 0

Views: 34

Answers (1)

DJV
DJV

Reputation: 4863

You can use factor to set the order of the levels and labels in both datasets.

require(tidyverse)

df1 %>% 
  mutate(cyl = factor(
    cyl, 
    levels = c("4", "6", "8"), 
    labels = c("Four", "Six", "Eight"))) %>% 
  ggplot(aes(disp, drat, color = cyl)) + 
  geom_point()

df2 %>% 
  mutate(cyl = factor(
    cyl, 
    levels = c("4", "6", "8"), 
    labels = c("Four", "Six", "Eight"))) %>% 
  ggplot(aes(disp, drat, color = cyl)) + 
  geom_point()

Result: enter image description here enter image description here

Sample data:

df1 <- select(mtcars[1:10, ], cyl, disp, drat)

df2 <- select(mtcars[11:20, ], cyl, disp, drat)

Upvotes: 1

Related Questions