0

I am doing a graph with different density functions and I need a specific order in the legend to be consistent with several figures I did before. My code is:

# latest version from github
# remotes::install_github("hughjonesd/truelies")
library("dplyr")
library(truelies)

d_Avoid = update_prior(heads = 73, N = 142, P = 0.8, prior = dunif)
d_NoAvoid = update_prior(heads =73, N = 141, P = 0.8, prior = dunif)
d_NoExt = update_prior(heads = 55, N = 140, P = 0.8, prior = dunif)
d_simult = update_prior(heads = 61, N = 146, P = 0.8, prior = dunif)


x = c(0,0.6)
    ggplot(data = data.frame(x = x), aes(x)) +
      geom_area(stat = "function", fun = d_Avoid, alpha = .5, aes(fill = "#FDE725FF")) +
      stat_function(fun = d_Avoid, color = "#FDE725FF", size = 1) +
      geom_area(stat = "function", fun = d_NoAvoid, alpha = .5, aes(fill = "#35B779FF")) +
      stat_function(fun = d_NoAvoid, color = "#35B779FF", size = 1) +
      geom_area(stat = "function", fun = d_NoExt, alpha = .5, aes(fill = "#31688EFF")) +
      stat_function(fun = d_NoExt, color = "#31688EFF", size = 1) +
      geom_area(stat = "function", fun = d_simult, alpha = .5, aes(fill = "#440154FF")) +
      stat_function(fun = d_simult, color = "#440154FF", size = 1) +
      xlab("Probability of lying") + ylab("Density") +  theme_tufte()  + 
      geom_rangeframe()+ theme(text=element_text(family="serif", size=12)) +
      scale_fill_identity(name = "", guide = 'legend',labels = c('No Externality', 'No Avoid', 'Simultaneous', 'Avoid'))+
      theme(legend.position="bottom") + guides(fill = guide_legend(reverse=TRUE))

This is the Figure the code creates

However, I need the order of the labels in the legend in the order 'Avoid', 'No Avoid', 'No Externality', and 'Simultaneous'.

I tried using:

scale_fill_identity(name = 'Treatment', guide = 'legend',labels = c('Avoid', 'No Avoid', 'No Externality', 'Simultaneous')) 

But this makes the mapping between the density function and the label wrong.

  • 1
    Use `breaks=` rather than `labels=` to just change the order. In the future, when asking a question make sure the code is [reproducible](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) so we can copy/paste into R to test it. This code doesn't define `d_Avoid`, `d_NoAvoid`, etc so it cannot be run. – MrFlick Aug 09 '21 at 18:25
  • Thanks @MrFlick, I changed the code to be reproducible (sorry for that). However, using breaks= rather than labels= did not solve my problem. – Daniel Parra Aug 10 '21 at 09:11

0 Answers0