R ggplot - Error stat_bin requires continuous x variable

后端 未结 4 574
南方客
南方客 2020-12-28 18:50

My table is data.combined with following structure:

\'data.frame\':   1309 obs. of  12 variables:
 $ Survived: Factor w/ 3 levels \"0\",\"1\",\"None\": 1 2 2         


        
相关标签:
4条回答
  • 2020-12-28 19:13

    I had the same issue but none of the above solutions worked. Then I noticed that the column of the data frame I wanted to use for the histogram wasn't numeric:

    df$variable<- as.numeric(as.character(df$variable))
    

    Taken from here

    0 讨论(0)
  • 2020-12-28 19:15

    Sum up the answer from the comments above:

    1 - Replace geom_histogram(binwidth=0.5) with geom_bar(). However this way will not allow binwidth customization.

    2 - Using stat_count(width = 0.5) instead of geom_bar() or geom_histogram(binwidth = 0.5) would solve it.

    0 讨论(0)
  • 2020-12-28 19:23

    As stated above use geom_bar() instead of geom_histogram, refer sample code given below(I wanted separate graph for each month for birth date data):

    ggplot(data = pf,aes(x=dob_day))+
    geom_bar()+
    scale_x_discrete(breaks = 1:31)+
    facet_wrap(~dob_month,ncol = 3)
    
    0 讨论(0)
  • 2020-12-28 19:31

    extractTitle <- function(Name) {     
    Name <- as.character(Name) 
    
      if (length(grep("Miss.", Name)) > 0) { 
        return ("Miss.")
      } else if (length(grep("Master.", Name)) > 0) { 
        return ("Master.") 
      } else if (length(grep("Mrs.", Name)) > 0) { 
        return ("Mrs.") 
      } else if (length(grep("Mr.", Name)) > 0) { 
        return ("Mr.") 
     } else { 
        return ("Other") 
      } 
    }
    
    titles <- NULL 
    
    for (i in 1:nrow(data.combined)){
      titles <- c(titles, extractTitle(data.combined[i, "Name"]))
    }
    
    data.combined$title <- as.factor(titles)
    
    ggplot(data.combined[1:892,], aes(x = title, fill = Survived))+
           geom_bar(width = 0.5) +
            facet_wrap("Pclass")+
             xlab("Pclass")+
             ylab("total count")+
             labs(fill = "Survived")  
    
    0 讨论(0)
提交回复
热议问题