I am creating a figure with a gradient fill scale. The values range from negative to positive, and I want white to represent 0.
I already know how to do this using scale_fill_gradientn, using scales::rescale on the min, 0, and max values for the scales to properly match.
v <- cbind.data.frame( comparison = c("c1","c2","c3","c4"),
log2FoldChange = c(0.1608255, 0.2741105, -0.3197456, -0.2285475))
ggplot(v, aes(x=log2FoldChange, y=comparison, fill=log2FoldChange)) +
geom_col() +
scale_fill_gradientn( values= scales::rescale( c(min(v$log2FoldChange),0,max(v$log2FoldChange)) ),
colors = c("deepskyblue","white","firebrick1")) +
theme_minimal() +
theme(aspect.ratio = 1) +
labs(x="log2 Fold Change", y="Comparison")
However, in this way, I have to refer to the original dataframe’s variable to get the min/max. This can be annoying if I have to repeat a similar plot using a slightly different variable or other datasets.
I have tried referring dynamically to the value on the x-axis with
values= scales::rescale( c(min(.x),0,max(.x)) )
> Error: object '.x' not found
or
values= scales::rescale( c(min(~.x),0,max(~.x)) )
> Error in min(~.x) : invalid 'type' (language) of argument
but neither worked.
The one I used it previously to modify secondary axes like:
scale_y_continuous(name = "Density",
sec.axis = sec_axis(~.x*50, name = "Counts")) +
I couldn’t find anywhere a way for ggplot commands to refer dynamically to the variables used for x and y-axes, as well as other ones.
Is that even possible with current ggplot coding?