How can I change the Y-axis figures into percentages in a barplot?

前端 未结 4 1466
清歌不尽
清歌不尽 2020-11-28 21:50

How can we change y axis to percent like the figure? I can change y axis range but I can\'t make it to percent. \"enter

相关标签:
4条回答
  • 2020-11-28 21:58

    Borrowed from @Deena above, that function modification for labels is more versatile than you might have thought. For example, I had a ggplot where the denominator of counted variables was 140. I used her example thus:

    scale_y_continuous(labels = function(x) paste0(round(x/140*100,1), "%"), breaks = seq(0, 140, 35))
    

    This allowed me to get my percentages on the 140 denominator, and then break the scale at 25% increments rather than the weird numbers it defaulted to. The key here is that the scale breaks are still set by the original count, not by your percentages. Therefore the breaks must be from zero to the denominator value, with the third argument in "breaks" being the denominator divided by however many label breaks you want (e.g. 140 * 0.25 = 35).

    0 讨论(0)
  • 2020-11-28 22:04

    Use:

    + scale_y_continuous(labels = scales::percent)
    

    Or, to specify formatting parameters for the percent:

    + scale_y_continuous(labels = scales::percent_format(accuracy = 1))
    

    (the command labels = percent is obsolete since version 2.2.1 of ggplot2)

    0 讨论(0)
  • 2020-11-28 22:06

    ggplot2 and scales packages can do that:

    y <- c(12, 20)/100
    x <- c(1, 2)
    
    library(ggplot2)
    library(scales)
    myplot <- qplot(as.factor(x), y, geom="bar")
    myplot + scale_y_continuous(labels=percent)
    

    It seems like the stat() option has been taken off, causing the error message. Try this:

    library(scales)
    
    myplot <- ggplot(mtcars, aes(factor(cyl))) + 
              geom_bar(aes(y = (..count..)/sum(..count..))) + 
              scale_y_continuous(labels=percent)
    
    myplot
    
    0 讨论(0)
  • 2020-11-28 22:08

    In principle, you can pass any reformatting function to the labels parameter:

    + scale_y_continuous(labels = function(x) paste0(x*100, "%")) # Multiply by 100 & add %  
    

    Or

    + scale_y_continuous(labels = function(x) paste0(x, "%")) # Add percent sign 
    

    Reproducible example:

    library(ggplot2)
    df = data.frame(x=seq(0,1,0.1), y=seq(0,1,0.1))
    
    ggplot(df, aes(x,y)) + 
      geom_point() +
      scale_y_continuous(labels = function(x) paste0(x*100, "%"))
    
    0 讨论(0)
提交回复
热议问题