我正在使用以下代码创建两个并排的饼图
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()
and quote
/ substitute
,但每次都会得到意想不到的结果。请指教。