Search code examples
rggplot2geom-bar

How to plot Multiple variables (i.e. Categories) in a Bar graph in ggplot2 in R


I am trying to plot a Bar graph for particular data set. The issue which i am facing is I am not able to understand how to use Multiple variables in the Bar graph. The data set which I am using is of this structure.

Source_Data <-
data.frame(
key = c(1, 1, 1, 2, 2, 2, 3, 3, 3),
Product_Name = c(
  "Table",
  "Table",
  "Chair",
  "Table",
  "Bed",
  "Bed",
  "Sofa",
  "Chair",
  "Sofa"
),
Product_desc = c("XX", "XXXX", "YY", "X", "Z", "ZZZ", "A", "Y", "A"),
Cost = c(1, 2, 3, 4, 2, 3, 4, 5, 6)
)

I am able to plot the Bar graph with the Cost in Y axis and key in x axis with Product_desc as each categories. I used the below code to do it.

ggplot(Source_Data, aes (key, Cost, fill = Product_desc)) + 
  geom_bar(stat = "identity", position = position_dodge()) + 
  scale_x_continuous(breaks = seq(2014, 2018, 2)) +
  scale_fill_brewer(palette = "Paired")

But I want to use Product name also in the graph to be displayed. The structure of data set is in such a manner.

Key --> Product_Name --> Product_desc and its corresponding cost.

This is an example from Excel.

enter image description here

I am sorry if that image was confusing. If there are any other suggestions to display the data please share it.


Solution

  • You can achieve something similar to the example from Excel using facets and some options.

    Source_Data %>% 
      ggplot(aes(Product_Name, Cost)) + 
      geom_col(aes(fill = Product_desc), position = position_dodge(preserve = "single")) + 
      facet_wrap(~key, scales = "free_x", strip.position = "bottom") +
      theme(strip.placement = "outside") + 
      theme_bw()
    

    Result:

    enter image description here