Why is some data missing in ggplot2 stacked bar graph?

Viewed 67

This is a dput() of a subset of my data as an example:

test <- structure(list(trt = c("one", "one", "one", "one", "one", "one", 
                               "one", "one", "one", "one", "one", "one", "one", "one", "one"
        ), parameter_name = c("A", "B", "C", "D", "E", "A", "B", "C", 
                              "D", "E", "A", "B", "C", "D", "E"),
        values = c(12.2, 45.5, 24.7, 11, 6.5, 12.2, 49, 22.8, 10.1, 6, 12, 47.7, 25.2, 9.3, 6)),
        row.names = c(NA, -15L), class = c("tbl_df", "tbl", "data.frame"))

I want to plot a stacked bar chart like this, only parameter_name "A" doesn't show.

ggplot(test, aes(trt, values, fill = parameter_name)) +
  stat_summary(geom = "bar", fun = "mean")

enter image description here

Setting position = "dodge2" suggests that A is there,

ggplot(test, aes(trt, values, fill = parameter_name)) +
  stat_summary(geom = "bar", fun = "mean", position = "dodge2")

enter image description here

but I cant work out why it isn't showing in the stacked version? Changing the position to "stack" also shows A, but I don't want the values as %

ggplot(test, aes(trt, values, fill = parameter_name)) +
  stat_summary(geom = "bar", fun = "mean", position = "stack")

I also checked if it was just a problem with the scale, but "A" is still not visible

ggplot(test, aes(trt, values, fill = parameter_name)) +
  stat_summary(geom = "bar", fun = "mean") +
  scale_y_continuous(limits = c(0, 60))

Can someone point out my mistake for me?

1 Answers

By default (position = "identity") each bar is displayed on top of each other. Since group A is the first to be plotted and is smaller than the other groups it is masked by them.

The answer is in your question: you need to use position = "stack":

ggplot(test, aes(trt, values, fill = parameter_name)) +
  stat_summary(geom = "bar", fun = "mean", position = "stack")

The values displayed are not %, it's just because the sum of your 5 mean values equals to 100

Related