Re-ordering bars in R's barplot()

前端 未结 3 638
闹比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 03:00

    I get the following,

    num <- c(1, 8, 4, 3, 6, 7, 5, 2, 11, 3)
    cat <- c(letters[1:10])
    data <- data.frame(num, cat)
    barplot(data[order(data[,1],decreasing=TRUE),][,1],names.arg=data[order(data[,1],decreasing=TRUE),][,2])
    

    The above code uses the order() function twice (see comments, below). To avoid doing this the results of the ordered data.frame can be stored in a new data.frame and this can be used to generate the barplot.

    num <- c(1, 8, 4, 3, 6, 7, 5, 2, 11, 3)
    cat <- c(letters[1:10])
    data <- data.frame(num, cat)
    data2  <- data[order(data[,1],decreasing=TRUE),]
    barplot(data2[,1],names.arg=data2[,2])
    

提交回复
热议问题