Ordering bars in barplot()

前端 未结 2 1912
遥遥无期
遥遥无期 2021-01-21 08:32

I have a dataframe, and one of the variables (let\'s call it Q1) has several levels: \"No use\", \"30 min\", \"1 hour\", \"2 hours\", \"3+ hours\".

How can I plot a barp

2条回答
  •  生来不讨喜
    2021-01-21 09:20

    As stated by Henrik, you need to get your data into a factor (at least this is the easiest easiest way to make this happen). Consider the following example with some fake data...

    #generate 1000 random uniform integers between 1 and 5
    data <- floor(runif(1000, 1,6)) 
    
    #make data a factor with given labels
    fdata <- factor(data,
                    labels = c("No use", 
                               "30 min", 
                               "1 hour", 
                               "2 hours", 
                               "3+ hours"))
    

    This can be done in base r with plot (barplot is not required when y is not specified)

    #in base R, just use plot - when y is missing, barplot is produced
    plot(fdata)
    

    You can also plot in ggplot2

    #in ggplot2
    require(ggplot2)
    
    #make a dataframe
    df <- data.frame(id = seq(1:length(fdata)),
                     fdata = fdata)
    
    #plot via geom_bar
    ggplot(df, aes(fdata)) + geom_bar()
    

    Proceeding from your original example, in addition to specifying levels, you are going to need to set ordered=TRUE as shown below. Otherwise, "No use" will still show up at the end of your list.

    #get data into a factor (provided data plus "No use")
    q1 <- c("No use"
            ,"1 hour"
            ,"1 hour"
            ,"30 min"
            ,"2 hours"
            ,"3+ hours"
            ,"3+ hours"
            ,"3+ hours"
            ,"3+ hours"
            ,"2 hours"
            ,"1 hour"
            ,"2 hours"
            ,"1 hour"
            ,"30 min")
    
    q1f = factor(q1,
                 levels = c("No use", 
                              "30 min", 
                              "1 hour", 
                              "2 hours", 
                              "3+ hours"),
                 ordered=TRUE)
    

    Then you can apply the plot logic shown above...

提交回复
热议问题