我目前正试图在r中订购一个条形图。该图在使用用于选择列的传递变量的函数中创建。这是基本功能:
plotting <- function(column_to_use) {
ggplot(iris, aes(x = Sepal.Length, ))+
aes_string(y = column_to_use)+
geom_col()
}
plotting("Species")
这产生了正确的情节,但我仍然需要订购它。我尝试过base-R reorder和forcats fct_reorder()。黑体显示代码差异
# reorder
plotting <- function(column_to_use) {
ggplot(iris, aes(x = Sepal.Length, ))+
aes_string(y = reorder(iris[column_to_use],Sepal.Width))+
geom_col()
}
plotting("Species")
> Error in tapply(X = X, INDEX = x, FUN = FUN, ...) :
object 'Sepal.Width' not found
我使用aes_string转换变量列名使用非标准的评估和图形,这不能在重新排序。遗憾的是,没有reorder_对应项可用。
# fct_reorder
plotting <- function(column_to_use) {
iris %>%
fct_reorder(iris[column_to_use],Sepal.Width) %>%
ggplot( aes(x = Sepal.Length))+
aes_string(y = column_to_use)+
geom_col()
}
plotting("Species")
> Error: `f` must be a factor (or character vector).
有什么更好的选择来获得按Sepal.Width排序的条形图?
aes_string
已被软弃用。尝试使用.data
:
library(ggplot2)
plotting <- function(column_to_use) {
ggplot(iris, aes(x = Sepal.Length,
y = reorder(.data[[column_to_use]], Sepal.Width)))+
geom_col()
}
plotting("Species")
可以转换为sym
bol,用!!
求值。输入
library(ggplot2)
plotting <- function(column_to_use) {
ggplot(iris, aes(x = Sepal.Length,
y = reorder(!! ensym(column_to_use), Sepal.Width)))+
geom_col()
}
plotting("Species")
plotting(Species)