关于r:创建函数以与ggplot2一起使用循环

Creating function to use loops with ggplot2

我正在尝试构建一个函数来与ggplot2一起使用循环。以下代码可以正常工作,我可以为数据框的每个变量获取条形图:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
    library(ggplot2)
    DF=data.frame(A=c(1,2,1,2,3,2,1,2,3,1,2,3),B=c(2,3,2,2,1,2,3,2,1,2,2,2),C=c(2,3,2,1,1,2,1,1,2,1,2,3))
    data_name<-data.frame("A","B","C")    

    Plot_Graph<-function(x,na.rm=T){
      nm=names(x)
      for (i in seq_along(nm)) {
        print(ggplot(x,aes(x=nm[i],y=x[,i],fill=factor(x[,i]))) +
                geom_bar(width=1,stat="identity")+
                coord_polar(theta="y")+
                ggtitle(data_name[1,i])+
                guides(fill=guide_legend(title=NULL))+
                scale_fill_discrete(breaks=c('1','2','3'),
                                    labels=c('A','B','C')))}}
     Plot_Graph(DF)

但是,当我尝试为每个变量创建饼图并仅观察到\\'1 \\'和\\'2 \\'(而不是为每个变量选择\\'3 \\')时,它给了我相同的错误每次:

Error: Aesthetics must be either length 1 or the same as the data (1): x, y, fill

我尝试了以下代码:

1
2
3
4
5
6
7
8
9
10
11
    Plot_Bar<-function(x,na.rm=T){
     nm=names(x)
     for (i in seq_along(nm)) {
       x1<-subset(x,nm[i] %in% c('1','2'))
       print(ggplot(x1,aes(x=nm[i],y=x1[,i],fill=factor(x1[,i]))) +
               geom_bar(width=1,stat="identity")+
               coord_polar(theta="y")+
               ggtitle(data_name[1,i])+
               guides(fill=guide_legend(title=NULL))+
               scale_fill_discrete(breaks=c('1','2'),
                             labels=c('A','B')))}}

但是它不起作用。我该怎么做才能为每个变量创建一个仅包含\\'1 \\'和\\'2 \\'的观察值的合适的条形图?

非常感谢。


您的subset()不正确。如果要打印x1,您会发现它始终为空。您可以仅在R中交换字符值和符号名称。在两种情况下,您需要使用不同类型的提取。这是一种重写子集

的可能方法

1
x1 <- x[x[[nm[i]]] %in% c('1','2'), ]

当需要使用字符串作为列名时,您不能(轻松)使用subset()