2

Following the nice example here: Create stacked barplot where each stack is scaled to sum to 100%

I generated a barplot for my data in which the results are presented as percent.

My data frame is:

small_df = data.frame(type = c('A','A','B','B'),
                      result = c('good','bad','good','bad'),
                      num_cases = c(21,72,87,2))

And my attempt to draw looks like so:

library(scales)
library(ggplot2)

ggplot(small_df,aes(x = type, y = num_cases, fill = result)) +
  geom_bar(position = "fill",stat = "identity") +
  scale_y_continuous(labels = percent, breaks = seq(0,1.1,by=0.1))

This all works fine and produces the a figure like so: enter image description here

However, I want to make the limits of the y axis to be 0-110% (I will later want to add a label on top so I need the space). Changing the line to:

scale_y_continuous(labels = percent, breaks = seq(0,1.1,by=0.1), limits = c(0,1.1))

fails with the following error:

Error: missing value where TRUE/FALSE needed

Any idea how to solve this?

Many thanks!!!

Community
  • 1
  • 1
N.M
  • 685
  • 1
  • 9
  • 22

1 Answers1

2

You can change the out of bounds option via oob or use coord_cartesian to set the limits. See info here

ggplot(small_df, aes(x = type, y = num_cases, fill = result)) +
    geom_bar(position = "fill", stat = "identity") +
    scale_y_continuous(labels = percent, breaks = seq(0, 1.1, by=0.1), 
                    oob = rescale_none, limits = c(0, 1.1))

ggplot(small_df, aes(x = type, y = num_cases, fill = result)) +
    geom_bar(position = "fill", stat = "identity") +
    scale_y_continuous(labels = percent, breaks = seq(0, 1.1, by=0.1)) +
    coord_cartesian(ylim = c(0, 1.1))

enter image description here

aosmith
  • 34,856
  • 9
  • 84
  • 118