Show percent % instead of counts in charts of categorical variables

前端 未结 8 2409
梦如初夏
梦如初夏 2020-11-22 06:06

I\'m plotting a categorical variable and instead of showing the counts for each category value.

I\'m looking for a way to get ggplot to display the perc

8条回答
  •  情话喂你
    2020-11-22 06:23

    Note that if your variable is continuous, you will have to use geom_histogram(), as the function will group the variable by "bins".

    df <- data.frame(V1 = rnorm(100))
    
    ggplot(df, aes(x = V1)) +  
      geom_histogram(aes(y = (..count..)/sum(..count..))) 
    
    # if you use geom_bar(), with factor(V1), each value of V1 will be treated as a
    # different category. In this case this does not make sense, as the variable is 
    # really continuous. With the hp variable of the mtcars (see previous answer), it 
    # worked well since hp was not really continuous (check unique(mtcars$hp)), and one 
    # can want to see each value of this variable, and not to group it in bins.
    ggplot(df, aes(x = factor(V1))) +  
      geom_bar(aes(y = (..count..)/sum(..count..))) 
    

提交回复
热议问题