创建函数以与ggplot2一起使用循环 [英] Creating function to use loops with ggplot2

查看:60
本文介绍了创建函数以与ggplot2一起使用循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to build a function to use loops with ggplot2. The following code works fine and I can get a bar chart for each variable of the data frame:

    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")时,每次都会给我相同的错误:

However, when I try to create a pie chart for each variable with observations of only '1' and '2' (not selecting '3' for each variable), it gives me the same error every time:

错误:美学的长度必须为1或与数据(1)相同:x,y,填充

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

我尝试了以下代码:

    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"的观测值的条形图?

but it did not work. What can I do so as to create an appropriate bar chart for each variable with only observations containing '1' and '2'?

非常感谢.

推荐答案

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

Your subset() isn't correct. If you were to print out x1 you'd see that it's always empty. You can just interchange character values and symbol names in R. You need to use different types of extraction in the two cases. Here's one possible way of re-rewriting the subset

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

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

you can't (easily) use subset() when you need to use character strings for column names.

这篇关于创建函数以与ggplot2一起使用循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆