stacked bar plot with ggplot

前端 未结 2 844
渐次进展
渐次进展 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

提交回复
热议问题