0

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.

camille
  • 16,432
  • 18
  • 38
  • 60
David Chris
  • 255
  • 4
  • 16
  • 1
    Do you want similar plot as in excel or something like this `Source_Data %>% gather(key2, val, starts_with("Product")) %>% ggplot(., aes(key, Cost, fill = val)) + geom_bar(stat = "identity", position = position_dodge()) + facet_wrap(~ key2)` – akrun Aug 15 '19 at 05:10
  • Your x-axis breaks seem to be unrelated to the actual data, and you therefore have no labels. Is that intentional? – camille Aug 15 '19 at 11:56
  • Maybe related / duplicate of https://stackoverflow.com/q/18165863/5325862 – camille Aug 15 '19 at 12:01

1 Answers1

1

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

neilfws
  • 32,751
  • 5
  • 50
  • 63
  • Thank you :) This works Awesome !!! I am actually trying to add Error bars to these graph. I am able to add the bars. But they are not getting placed in the exact place which I want . That is each error bar is not getting placed on its corresponding Bar. Instead they are mismatched. Can you please suggest/advice me on this. – David Chris Aug 21 '19 at 02:49
  • 1
    Best to ask a new question for a new issue. – neilfws Aug 21 '19 at 03:01