I want to be able to define the fill=
as one of the arguments in a function. First, here is what my tibble looks like:
> x
# A tibble: 16 × 6
popA popB genome chr1 chr2 chr3
<chr> <chr> <dbl> <dbl> <dbl> <dbl>
1 CG GOE 0.0165 0.0128 0.0176 0.0176
2 CG SC 0.0173 0.0159 0.0171 0.0184
3 DEL SC 0.0180 0.0150 0.0164 0.0218
4 DEL GOE 0.0165 0.0168 0.0148 0.0183
5 GOE HPK 0.0381 0.0425 0.0340 0.0399
6 HPK KPA 0.0166 0.0192 0.0160 0.0156
7 HPK SC 0.0383 0.0411 0.0348 0.0405
8 HPK WAI 0.0121 0.0133 0.0113 0.0123
9 CG KPA 0.0361 0.0359 0.0361 0.0363
10 DEL KPA 0.0322 0.0314 0.0318 0.0332
11 KPA LIH 0.0150 0.0160 0.0150 0.0143
12 GOE LIH 0.0395 0.0429 0.0360 0.0413
13 LIH SC 0.0349 0.0363 0.0327 0.0365
14 LIH WAI 0.0105 0.0132 0.00978 0.00954
15 CG WAI 0.0234 0.0224 0.0219 0.0258
16 DEL WAI 0.0209 0.0182 0.0188 0.0252
And I’d like to have a function where I can define geom_tile(aes(fill=region))
(see function below), but that does not seem to be working. The function:
xfn <- function(df, region){
df %>%
ggplot(aes(x = popA, y = popB)) +
geom_tile(aes(fill=region)) +
coord_equal() +
xlab("Sample") +
ylab("Sample")
}
However, if I try to run it like this: xfn(x, chr1)
, I get the following error:
Error in `geom_tile()`:
! Problem while computing aesthetics.
ℹ Error occurred in the 1st layer.
Caused by error:
! object 'chr1' not found
I can take the “region” argument out of the function (i.e., explicitly specify fill=
in the function), and it works. Like this:
xfn <- function(df){
df %>%
ggplot(aes(x = popA, y = popB)) +
geom_tile(aes(fill=chr1)) +
coord_equal() +
xlab("Sample") +
ylab("Sample")
}
xfn(x) #This produces the plot that I want
So what gives…? Is there a way to make the first function functional?
Sorry if there is an obvious answer, or this is a redundant question with another post I didn’t see, but I did a lot of Googling and tinkering (to no avail) before posting here.
Thanks in advance!
Luke Campillo is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1