2

I have a dataset with three columns (one categorical column and two-discrete variables column). I want to make a stacked bar plot to compare the values of the two discrete variables for each category. However, I get continuous coloring rather than discrete colors.

Reproducible code

sampleData <-  data.frame(grp = c("A","B", "C"),
                          var_1 = c(15,20, 25),
                          var_2 = c(12, 13, 20))
sampleData

p <- ggplot(sampleData, aes(x = grp, y = var_1, fill= var_2)) +
  geom_bar( stat="identity", position = "fill")+
  coord_flip()+ theme_bw()
p

Output from above code

Instead, what I want is

Expected output

*Var2 will always be smaller than its corresponding Var1 value for a particular category.

Thanks for the help!

1 Answer 1

1

Your problem here is that you haven't fixed your tibble from Wide to Long.

FixedData <- sampleData %>%
  pivot_longer(cols = c("var_1", "var_2"), names_prefix = "var_", 
               names_to = "Variable Number", values_to = "ValueName")

Once you do this, the problem becomes much easier to solve. You only need to change a few things, most notably the y, fill, and position variables to make it work.

p2 <- ggplot(FixedData, aes(x = grp, y = ValueName, fill = `Variable Number`)) +
  geom_bar(stat="identity", position = "stack")+
  coord_flip()+ theme_bw()

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

Comments

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.