How to get percentages on the y axes in an alluvial or sankey plot?

后端 未结 3 956
眼角桃花
眼角桃花 2021-01-16 02:53

I realized this graph using ggplot2 and I\'d like to change y axes to percentages, from 0% to 100% with breaks every 10. I know I can use:

+ scale_y         


        
相关标签:
3条回答
  • 2021-01-16 03:33

    Simply normalising your y-values seems to do the trick:

    library(ggplot2)
    
    ggplot(mtcars, aes(x = cyl, y = mpg/max(mpg))) +
      geom_point() +
      scale_y_continuous(label = scales::label_percent())
    

    Created on 2020-05-19 by the reprex package (v0.3.0)

    0 讨论(0)
  • 2021-01-16 03:43

    I assume You will need to create a new column of the percentages, by taking the total number of rows, and then dividing each "value" in your column by the total to get what percentage it represents.

    0 讨论(0)
  • 2021-01-16 03:46

    Using the scale argument in percent_format this can be achieved like so:

    PIPPO <- data.frame("ID"=rep(c(1:20),2), "time"=c(rep(1,20),rep(2,20)), "value"=c("B","G","B","G","B",rep("G",3),rep("B",2),"G",rep("B",3),"G",rep("B",6),"G","B","G","B",rep("G",3),rep("B",2),"G",rep("B",3),"G","B","switch",rep("B",2),"switch"))
    
    library(ggplot2)
    library(ggalluvial)
    
    n_id <- length(unique(PIPPO$ID))
    
    ggplot(PIPPO, 
           aes(x = time, stratum = value, alluvium = ID,
               fill = value, label = value)) +
      scale_fill_brewer(type = "qual" , palette = "Set3") +
      scale_y_continuous(label = scales::percent_format(scale = 100 / n_id)) +
      geom_flow(stat = "flow", knot.pos = 1/4, aes.flow = "forward", color = "gray",) + 
      geom_stratum() +
      theme(legend.position = "bottom") 
    

    Created on 2020-05-19 by the reprex package (v0.3.0)

    0 讨论(0)
提交回复
热议问题