问题描述
我正在尝试编写绘图功能,您可以在其中传递裸列名称以选择要绘制的列.我还希望能够指定一个字符串作为颜色.
I am trying to write a plotting function where you can pass bare column names to select which columns are plotted. I would like also to be able to specify a string as the color.
我发现如果要将字符串传递给aes_string,则需要使用shQuote.现在我的问题是找出是否传递了裸名或字符串.我该怎么办?
I have found that I need to use shQuote if I want to pass a string to aes_string. Now my problem is to figure out if a bare name or a string was passed.How would I do this?
dat <- data.frame(
time = factor(c("Lunch","Dinner"), levels=c("Lunch","Dinner")),
total_bill = c(14.89, 17.23)
)
plot_it <- function(dat, x,y, fill){
require(rlang)
require(ggplot2)
x <- enquo(x)
y <- enquo(y)
fill <- enquo(fill)
xN <- quo_name(x)
yN <- quo_name(y)
fillN <- quo_name(fill)
ggplot(data=dat, aes_string(x=xN, y=yN, fill=fillN)) +
geom_bar(stat="identity")
}
这有效:
plot_it(dat, time, total_bill, time)
这不是:
plot_it(dat, time, total_bill, "grey")
请注意,这需要最新版本的rlang和ggplot2.
Note that this requires the newest versions of rlang and ggplot2.
推荐答案
从您的答案和,这是一个版本:
- 解决您原来的问题
- 像Eumenedies一样防止不必要的传说
- 提供可以无误添加到的ggplot对象
- 根据Eumenedies的建议使用更合适的
geom_col
主要技巧是,如果 fill
不是情节中的一个因素,则希望将其放在 aes
/ aes_string
之外阻止.
The main trick is that, if fill
isn't a factor in the plot, you want it outside of the aes
/ aes_string
block.
plot_it <- function(dat, x, y, fill) {
lst <- as.list(match.call())
xN <- quo_name(enquo(x))
yN <- quo_name(enquo(y))
if(is.character(lst$fill)) {
p <- ggplot(data=dat, aes_string(x=xN, y=yN)) +
geom_col(fill = fill)
} else {
p <- ggplot(data=dat, aes_string(x=xN, y=yN, fill = quo_name(enquo(fill)))) +
geom_col()
}
return(p)
}
plot_it(dat, time, total_bill, time)
plot_it(dat, time, total_bill, "blue")
plot_it(dat, time, total_bill, "blue") + geom_point()
您可以通过将第二种情况下的 fill
美观性移至 geom_col
调用来缩短 if
块,但这会扩展为如果添加更多的几何图形,则采用另一种方法.
You could make the if
block shorter by moving the fill
aesthetic in the second case to the geom_col
call, but that will extend in a different way if you add more geoms.
此外,一旦将 ggplot
更新为支持 rlang
,最好避免使用 aes_string
和 quo_name
组合,只需使用 !! fill
.
Also, once ggplot
is updated to support rlang
, it would be cleaner to avoid aes_string
and quo_name
combination and just use !!fill
.
请注意,假设存在 fill
因素,如果它总是与 x
因素相同,那么拥有一个版本可能更有意义其中 fill
是可选参数.如果包含该参数,则只会覆盖默认的每个因数颜色.
Note that, assuming that the fill
factor exists, if it's always going to be the same as the x
factor, it would probably make more sense to have a version where fill
is an optional argument. You would only overwrite the default per-factor color if the argument is included.
这篇关于如何检测裸变量或字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!