r - 使用 ggplot2 绘制饼图

标签 r ggplot2 pie-chart non-standard-evaluation

我使用以下代码创建两个并排饼图

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")

enter image description here

关于r - 使用 ggplot2 绘制饼图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59451820/

相关文章:

r - 根据先前的结果并行化 for 循环

r - RStudio没有选择我告诉它在读取文件时使用的编码

java - 无法完成饼图的圆圈

r - 在 R 中使用 system2() 调用 shp2pgsql

r - 遍历 dplyr 中的列

r - ggplot2 中两个数据集的两个不同比例的 y 轴

r - 如何完全删除面条之间的空格(以连接 geom_rect 'background' )?

r - 如何将自定义系列标签添加到 R 的 ggplot 中的图例?

html - 如何通过 CSS 更改 nvd3 图表填充和描边颜色

css - 如何防止 Kendo UI 饼图工具提示在父 Div 之外绘制?