stacked bar plot with ggplot

前端 未结 2 763
渐次进展
渐次进展 2021-01-28 04:26

I\'m trying to make a stacked bar plot with the following dataframe:

 totalleft
        1S 2S 3S 4S 12S 25S      tests
A-000   5  0 10 10   0  NA       A-000
A-0         


        
相关标签:
2条回答
  • 2021-01-28 05:01

    So you need to reshape the data. You want a stacked barplot, so you will need to tell ggplot about variables 1S, 2S ... and tests.

    #let's melt the data
    #library(reshape2)
    data.plot.m <-melt(data.plot, id.vars = "tests") #I stored your data in data.plot
    data.plot.m$variable <-gsub("X","",data.plot.m$variable) 
    #as R doesn't like variable names beginning with numbers,
    #it adds an 'X' automatically when
    #we load the data with read.table so we remove this from melted data
    
    #now we plot the data
    ggplot(data.plot.m,aes(y = value,x = variable,fill = tests)) +
    geom_bar(stat = "identity")
    

    enter image description here You will notice the order of the plots are different. We will need to reorder your variable:

    data.plot.m$variable <- factor(data.plot.m$variable, levels = unique(data.plot.m$variable))
    #now plot again
    ggplot(data.plot.m,aes(y = value,x = variable,fill = tests))+
    geom_bar(stat = "identity") 
    

    enter image description here

    I just realized you wanted this instead

    ggplot(data.plot.m,aes(y=value,x=tests,fill=variable))+geom_bar(stat="identity")
    

    and with the x-axis tick labels rotated

    ggplot(data.plot.m,aes(y=value,x=tests,fill=variable))+geom_bar(stat="identity") + theme(axis.text.x = element_text(angle=90))
    

    enter image description here Note how I switched x and fill

    0 讨论(0)
  • This seems like what you wanted??

    library(reshape2)
    library(ggplot2)
    
    gg <- melt(totalleft,id="tests")
    ggplot(gg) +
      geom_bar(aes(x=tests, y=value, fill=variable), stat="identity")+
      theme(axis.text.x=element_text(angle=-90, vjust=.2, hjust=0))
    

    melt(...) converts your data frame from "wide" format (groups in different columns) to "long" format (all the values in one column (called value), and groups distinguished by a separate column (called variable).

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