【发布时间】:2021-02-28 10:46:20
【问题描述】:
我目前正在尝试在 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 排序的条形图有哪些更好的选择?
【问题讨论】:
标签: r function dplyr factors nse