Home > Software design >  Ordering legend values ggplot
Ordering legend values ggplot

Time:10-07

I was trying to ordering the labels of a plot but no matter what I do it doesn't change.

This is a dummy data frame because mine is way to big but I would get the same result

df <- data.frame(treatment= c("C", "3", "4", "5", "10","HT"), 
                 day1 = c(0.23, 0.16, 0.34, 0.21, 0.17,0.34),
                 day2=c(0.18,0.13,0.27,0.17,0.11,0.23),
                 day4=c(0.15,0.08,0.20,0.14,0.05,0.17))

I plot it using this code

df %>%
  pivot_longer(-treatment, names_to = "days", names_prefix = "day") %>% 
  mutate(days = as.integer(days),
         treatment = as.factor(treatment)) %>% 
  ggplot(aes(days, value, color = treatment))  
  geom_line() 
  ylab(expression(Transpiration (g/h))) xlab(expression(Days))  theme_dark()  theme(text = element_text(size = 20))

After this the legend order is 10,3,4,5,C,HT. So I tried to change to C,3,4,5,10,HT

df %>%
  pivot_longer(-treatment, names_to = "days", names_prefix = "day") %>% 
  mutate(days = as.integer(days),
         treatment = as.factor(treatment)) %>% 
  ggplot(aes(days, value, color = treatment))  
  geom_line() 
  ylab(expression(Transpiration (g/h))) xlab(expression(Days))  theme_dark()  theme(text = element_text(size = 20)) 
  scale_fill_discrete(breaks=c("C","3","4","5","10","HT"))

But I keep getting the same results. Any suggestions please? also how can I get the legend into the graph itself and delete the title of the legend. Thank you for all the helpenter image description here

CodePudding user response:

You can manually provide the limits to the scale if you want a particular order. Also you're using a fill legend for a colour aesthetic, which probably explains why your code wasn't working.

library(ggplot2)
library(tidyr)
library(dplyr)

df <- data.frame(treatment= c("C", "3", "4", "5", "10","HT"), 
                 day1 = c(0.23, 0.16, 0.34, 0.21, 0.17,0.34),
                 day2=c(0.18,0.13,0.27,0.17,0.11,0.23),
                 day4=c(0.15,0.08,0.20,0.14,0.05,0.17))

df %>%
  pivot_longer(-treatment, names_to = "days", names_prefix = "day") %>% 
  mutate(days = as.integer(days),
         treatment = as.factor(treatment)) %>% 
  ggplot(aes(days, value, color = treatment))  
  geom_line()  
  scale_colour_discrete(limits = df$treatment)

Created on 2021-10-06 by the reprex package (v2.0.1)

To delete the title and place the legend inside the panel, you can use

  scale_colour_discrete(limits = df$treatment, name = NULL)  
  theme(legend.position = c(1, 1),
        legend.justification = c(1, 1))
  • Related