0

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)

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:

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

I tried the following code:

    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')))}}

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'?

Many thanks.

2
  • Possible duplicate of Looping over variables in ggplot Commented Jun 14, 2018 at 20:41
  • @divibisan Thanks but in my case I want to select observations with specific values (i.g. '1' and '2') to create a chart for each variable Commented Jun 14, 2018 at 20:46

1 Answer 1

1

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'), ]

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.