Re-ordering bars in R's barplot()

前端 未结 3 627
闹比i
闹比i 2020-12-06 02:25

What I want to achieve is exactly the same that was already asked here (and specifically using R\'s base graphics, not packages like ggplot or lattice

3条回答
  •  时光取名叫无心
    2020-12-06 02:36

    you can use ggplot to do this

    library("ggplot2")
    num <- c(1, 8, 4, 3, 6, 7, 5, 2, 11, 3)
    cat <- c(letters[1:10])
    data <- data.frame(num, cat)    
    ggplot(data,aes(x= reorder(cat,-num),num))+geom_bar(stat ="identity")
    

    The result is as shown below

    Using base functions

    df <- data[order(data$num,decreasing = TRUE),]
     barplot(df$num,names.arg = df$cat)
    

提交回复
热议问题