How to plot 2 categorical variables on X-axis and two continuous variables as “fill” using ggplot2 package?

后端 未结 1 1824
谎友^
谎友^ 2020-12-29 15:40

I have a dataset that has two categorical variables, viz., Year and Category and two continuous variables TotalSales and Average

相关标签:
1条回答
  • 2020-12-29 15:58

    You need to first reformat your data, as @EDi showed you how to in one of your older questions (ggplot : Multi variable (multiple continuous variable) plotting) and @docendo discimus suggested in the comments.

    library(reshape2)
    dat_l <- melt(dat, id.vars = c("Year", "Category"))
    

    Then you can use faceting like so:

    library(ggplot2)
    p <- ggplot(data = dat_l, aes(x = Category, y = value, group = variable, fill = variable))
    p <- p + geom_bar(stat = "identity", width = 0.5, position = "dodge")
    p <- p + facet_grid(. ~ Year)
    p <- p + theme_bw()
    p <- p + theme(axis.text.x = element_text(angle = 90))
    p
    

    enter image description here

    If you are particularly interested in making the figure more consistent with an Excel-look, there are some strategies in the answer here that might be helpful: How do I plot charts with nested categories axes?.

    Your original data in an easier to paste format:

    dat <- structure(list(Year = c(2013L, 2013L, 2013L, 2013L, 2013L, 2014L, 
    2014L, 2014L, 2014L, 2014L), Category = structure(c(1L, 2L, 3L, 
    4L, 5L, 1L, 2L, 3L, 4L, 5L), .Label = c("Beverages", "Condiments", 
    "Confections", "Dairy Products", "Seafood"), class = "factor"), 
        TotalSales = c(102074.29, 55277.56, 36415.75, 30337.39, 53019.98, 
        81338.06, 55948.82, 44478.36, 84412.36, 65544.19), AverageCount = c(22190.06, 
        14173.73, 12138.58, 24400, 27905.25, 35400, 19981.72, 24710, 
        32466, 14565.37)), .Names = c("Year", "Category", "TotalSales", 
    "AverageCount"), class = "data.frame", row.names = c(NA, -10L
    ))
    
    0 讨论(0)
提交回复
热议问题