2

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

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,但每次都会得到意想不到的结果。请指教。

4

2 回答 2

2

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

在此处输入图像描述

于 2019-12-23T08:23:33.153 回答
1

您可以在绘图功能之前定义变量:

Var1 = "cyl"
Var2 = "gear"

然后在绘图函数中使用这些变量:

ggplot(data=mtcars, aes(x=factor(1), stat="bin", fill=mtcars[,Var1])) + 
  geom_bar(position="fill") + 
  ggtitle("Cylinders by Gears") + xlab("") + ylab("Gears") + 
  facet_grid(facets=. ~ mtcars[,Var2]) + 
  coord_polar(theta="y") + theme_void()

如果你想用这个写一个函数,你可以这样做:

plot_function = function(dataset,Var1,Var2) {
  ggplot(data=dataset, aes(x=factor(1), stat="bin", fill=dataset[,Var1])) + 
    geom_bar(position="fill") + 
    ggtitle(paste0(Var1, " by ", Var2)) + xlab("") + ylab(Var2) + 
    guides(fill = guide_legend(title = Var1))+
    facet_grid(facets=. ~ dataset[,Var2]) + 
    coord_polar(theta="y") + theme_void()
}

并像这样使用它:

plot_function(mtcars, "cyl","gear")

它回答了你的问题吗?

于 2019-12-23T08:02:53.087 回答