Search code examples
rggplot2percentagegeom-bar

How to set the ylim for y_continuous in R?


I am new to R and I want to know how to set the limit percentage of scale_y_continuous in R. I want to set the ylim btw 0% to 40% but it did not work :(

Here is my code:

library(ggplot2)
library(scales)
dat <- data.frame(
  time = factor(c("Breakfast","Lunch","Lunch","Dinner"), levels=c("Breakfast","Lunch","Dinner")),
  total_bill = c(12.75,14.89,"*",17.23)
)
#clear the * row and save the new dataframe
dat1 <- droplevels(subset(dat, total_bill != "*"))
dat1 <- type.convert(dat1, as.is = TRUE)

# add a column for percent of total bill
dat1$perc <- ((dat1$total_bill)/sum(dat1$total_bill)) * 100

# example plot with some minimal formatting
ggplot(dat1, aes(time,perc)) +
  geom_bar(aes(y=perc),stat="identity",fill = "#4B0082") +
  geom_text(aes(label = scales::percent(perc),y=perc),
            vjust=.5,hjust=1.2,color="white")+
  scale_y_continuous(labels = scales::percent,limits = c(0,40))+
  labs(title="x",y="%")+
  coord_flip()

Any help would be much appreciated


Solution

  • There's a couple of things, the scale displays numbers that area a proportion as a percentage, so there's no need to multiply by 100. Then the limits get set to c(0,0.4) for 40%:

        library(ggplot2)
      library(scales)
      dat <- data.frame(
        time = factor(c("Breakfast","Lunch","Lunch","Dinner"), levels=c("Breakfast","Lunch","Dinner")),
        total_bill = c(12.75,14.89,"*",17.23)
      )
      #clear the * row and save the new dataframe
      dat1 <- droplevels(subset(dat, total_bill != "*"))
      dat1 <- type.convert(dat1, as.is = TRUE)
    
      # add a column for percent of total bill
      dat1$perc <- ((dat1$total_bill)/sum(dat1$total_bill))
    
      # example plot with some minimal formatting
      ggplot(dat1, aes(time,perc)) +
        geom_bar(aes(y=perc),stat="identity",fill = "#4B0082") +
        geom_text(aes(label = scales::percent(perc),y=perc),
                  vjust=.5,hjust=1.2,color="white")+
        scale_y_continuous(labels = scales::percent,limits = c(0,0.4))+
        labs(title="x",y="%")+
        coord_flip()