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.
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.