N.M N.M - 3 months ago 39
R Question

Manipulating Y axis limits does not work (ggplot2 percent bar plot)

Following the nice example here:
Create Stacked percent barplot in R

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!!!

Answer

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

Comments