ggplot:显示%而不是计数。熔化的data.frame中的多个变量

时间:2013-05-04 19:40:17

标签: r ggplot2

我读了this post关于显示%而不是计数的ggplot,但是当我有一个由多个因子变量组成的融合数据框时,我无法使它工作。

这给了我一个情节,其中酒吧仍然显示计数而不是我想要的%。

 # Data
  head(sabat)
     V1 V2 V3 V4 V5 V6 V7 V8
   1  2  2  2  2  2  2  1  2
   2  2  1  2  1  2  1  1  2
   3  2  2  2  2  2  2  2  1
   4  1  2  2  2  2  2  2  2
   5  2  1  2  2  2  2  1  2
   6  2  1  2  1  2  1  1  2

  # melt data.frame
    sabat.m        <- melt(sabat)

  # set 2 to NA because as only want to plot the yes answers (1=yes, 2=no)
  sabat.m$value[sabat.m$value==2] <- NA
  sabat.m <- na.omit(sabat.m)

  # Factor it
  sabat.m$value  <- factor(sabat.m$value)

  #structure of the melted data.frame
  str(sabat.m)

   data.frame': 1020 obs. of  2 variables:
   $ variable: Factor w/ 8 levels "V1","V2","V3",..: 1 1 1 1 1 1 1 1 1 1 ...
   $ value   : Factor w/ 1 level "1": 1 1 1 1 1 1 1 1 1 1 ...
   - attr(*, "na.action")=Class 'omit'  Named int [1:2412] 1 2 3 5 6 7 8 10 11 12 ...
   .. ..- attr(*, "names")= chr [1:2412] "1" "2" "3" "5" ...

  # Plot it
  p <- ggplot(sabat.m, aes(x = variable)) +  
  geom_bar(aes(y = (..count..)/sum(..count..)), binwidth = 25) + 
  scale_y_continuous(labels = percent_format()) +
  coord_flip()

  p

提前致谢

0 个答案:

没有答案