I'm elaborating a function that creates a custom ggplot plot. The problem is that when I invoke the function and pass a df column name (let's say 'AREA') of a column that I'd like to use as the value of another variable (let`s say var) I get an Error: Discrete value supplied to continuous scale. But when I use that custom function with the same value (character 'AREA', not the variable var = 'AREA') it works. Moreover, when I use the exact ggplot code and pass the column name as variable var it also works fine.
Reproducible example:
library(sf)
library(tidyverse)
library(viridis)
library(rvest)
nc <- read_sf(system.file("shape/nc.shp", package = "sf"))
### Custom function
p_plot <- function(data,var){
ggplot(nc) +
geom_sf(aes(fill = !!ensym(var))) +
scale_fill_gradientn("Area",colors = viridis(10)
) +
ggtitle("Area of counties in North Carolina") +
theme_bw()
}
nc <- read_sf(system.file("shape/nc.shp", package = "sf"))
var <- j<- 'AREA'
### This one works
ggplot(nc) +
geom_sf(aes(fill = !!ensym(var))) +
scale_fill_gradientn("Area",colors = viridis(10)
) +
ggtitle("Area of counties in North Carolina") +
theme_bw()
### This one also works
p_plot(data, "AREA")
### This one doesn't work:
### Error: Discrete value supplied to continuous scale
p_plot(data, j)