1

When using scale_fill_continuous_diverging from colorspace inside a for loop or function does not paste for the name of legend title and through an error as in the example below.

library("ggplot2")
library(colorspace)
set.seed(100)
df <- data.frame(country = LETTERS, V = runif(26, -40, 40))
df$country = factor(LETTERS, LETTERS[order(df$V)]) # reorder factors

    fun_plt<-function(x){
      
      x<-df
      gg <- ggplot(df, aes(x = country, y = V, fill = V)) +
        geom_bar(stat = "identity") +
        labs(y = "Under/over valuation in %", x = "Country") +
        coord_flip() + theme_minimal()
      gg
     #Lets say want to paste test in the leged when running through function
      tt<-"test"
  
      gg2<-gg+
        scale_fill_continuous_diverging(name=paste0(tt,"V"),
                                        palette = "Blue-Red 3", l1 = 30, l2 = 100, p1 = .9, p2 = 1.2)
      gg2
    }


fun_plt(df)

It works well independently but gives an error when run inside a function.

1
  • Hm. Looks like a bug. Maybe you should raise an issue on the GitHub site. As a workaround you could add your legend label via labs(fill = paste0(tt,"V"))
    – stefan
    Feb 4, 2021 at 16:30

1 Answer 1

2

This was a problem with the way how the underlying ggplot2 scale functions (discrete_scale, continuous_scale, binned_scale) were called by the scale functions in colorspace. The calling environment was not always preserved and hence the non-standard evaluation of some arguments like name did not work as intended.

I have fixed the problem now in version 2.0-1, the current development version of colorspace on R-Forge. Installing this should fix the bug:

install.packages("colorspace", repos = "http://R-Forge.R-project.org")

Update: Meanwhile this has also been released through CRAN.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.