Making a stacked bar plot for multiple variables - ggplot2 in R

后端 未结 2 1060
你的背包
你的背包 2020-11-29 05:55

I have some problems with making a stacked bar chart in ggplot2. I know how to make one with barplot(), but I wanted to use ggplot2 because it\'s very easy to make the bars

2条回答
  •  甜味超标
    2020-11-29 06:53

    First, some data manipulation. Add the category as a variable and melt the data to long format.

    dfr$category <- row.names(dfr)
    mdfr <- melt(dfr, id.vars = "category")
    

    Now plot, using the variable named variable to determine the fill colour of each bar.

    library(scales)
    (p <- ggplot(mdfr, aes(category, value, fill = variable)) +
        geom_bar(position = "fill", stat = "identity") +
        scale_y_continuous(labels = percent)
    )
    

    (EDIT: Code updated to use scales packages, as required since ggplot2 v0.9.)

    enter image description here

提交回复
热议问题