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.

3
  • 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) Commented Aug 15, 2019 at 5:10
  • Your x-axis breaks seem to be unrelated to the actual data, and you therefore have no labels. Is that intentional? Commented Aug 15, 2019 at 11:56
  • Maybe related / duplicate of stackoverflow.com/q/18165863/5325862 Commented Aug 15, 2019 at 12:01

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

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.
Best to ask a new question for a new issue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.