我使用以下代码创建两个并排饼图
library(ggplot2)
mtcars$cyl <- factor(mtcars$cyl) # converts to a categorical variable
mtcars$gear <- factor(mtcars$gear) # converts to a categorical variable
p <- ggplot(data=mtcars, aes(x=factor(1), stat="bin", fill=cyl)) + geom_bar(position="fill") # Stacked bar chart
p <- p + ggtitle("Cylinders by Gears") + xlab("") + ylab("Gears") # Adds titles
p <- p + facet_grid(facets=. ~ gear)
p <- p + coord_polar(theta="y") + theme_void()
p
这很好用,但不幸的是我需要以编程方式执行此操作。特别是,我需要能够将“fill = cyl”和“facets = .~ gear”更改为其他变量,作为函数的一部分。理想情况下,我可以将变量名称作为字符串传递给上面的代码。
我尝试过使用aes_string()
和quote
/substitute
,但每次都会得到意想不到的结果。请指教。
最佳答案
对于 fill
参数,我们可以使用 sym
将字符串转换为符号,然后使用 !!
对其进行评估,而对于 facet_grid
我们可以使用reformulate
。
library(ggplot2)
library(rlang)
apply_fun <- function(data, fill_col, facet_col) {
ggplot(data=data, aes(x=factor(1), stat="bin", fill= !!sym(fill_col))) +
geom_bar(position="fill") +
ggtitle("Cylinders by Gears") + xlab("") + ylab("Gears") +
facet_grid(reformulate(facet_col, ".")) +
coord_polar(theta="y") + theme_void()
}
apply_fun(mtcars, "cyl", "gear")
关于r - 使用 ggplot2 绘制饼图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59451820/