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.
labs(fill = paste0(tt,"V"))