Avoid ggplot sorting the x-axis while plotting geom_bar()

前端 未结 4 708
情书的邮戳
情书的邮戳 2020-11-28 06:32

I have the following data which I want to plot with ggplot:

SC_LTSL_BM    16.8275
SC_STSL_BM    17.3914
proB_FrBC_FL   122.1580
preB_FrD_FL    18.5051
B_Fo_S         


        
相关标签:
4条回答
  • 2020-11-28 06:57

    Here is an approach that does not modify the original data, but uses scale_x_discrete. From ?scale_x_discrete "Use limits to adjust the which levels (and in what order) are displayed" For example:

    dat <- read.table(text=
                    "SC_LTSL_BM    16.8275
                  SC_STSL_BM    17.3914
                  proB_FrBC_FL   122.1580
                  preB_FrD_FL    18.5051
                  B_Fo_Sp    14.4693
                  B_GC_Sp    15.4986", header = FALSE, stringsAsFactors = FALSE)
    # plot
    library(ggplot2)
    ggplot(dat,aes(x=V1,y=V2))+
      geom_bar(stat="identity")+
      scale_x_discrete(limits=dat$V1)
    

    0 讨论(0)
  • 2020-11-28 06:59

    You can also just re-order the corresponding factor as described here

    x$name <- factor(x$name, levels = x$name[order(x$val)])
    
    0 讨论(0)
  • 2020-11-28 06:59

    dplyr lets you easily create a row column that you can reorder by in ggplot.

    library(dplyr)
    dat <- read.table("...") %>% mutate(row = row_number())
    ggplot(df,aes(x=reorder(V1,row),y=V2))+geom_bar()
    
    0 讨论(0)
  • 2020-11-28 07:12

    You need to tell ggplot that you've got an ordered factor already, so it doesn't automatically order it for you.

    dat <- read.table(text=
    "SC_LTSL_BM    16.8275
    SC_STSL_BM    17.3914
    proB_FrBC_FL   122.1580
    preB_FrD_FL    18.5051
    B_Fo_Sp    14.4693
    B_GC_Sp    15.4986", header = FALSE, stringsAsFactors = FALSE)
    
    # make V1 an ordered factor
    dat$V1 <- factor(dat$V1, levels = dat$V1)
    
    # plot
    library(ggplot2)
    ggplot(dat,aes(x=V1,y=V2))+geom_bar(stat="identity")
    

    enter image description here

    0 讨论(0)
提交回复
热议问题