Histogram of factor with labels on frequency bars

非 Y 不嫁゛ 提交于 2019-12-11 07:24:36

问题


Typically if I need to make a histogram with labels I will use hist(rnorm(100),labels=TRUE). However if my data is factors then I need to use plot(as.factor(c("a","a","b"))). The issue with this is that labels=TRUE will not work with plot; how do I fix this?

I preferably want a solution without needing to load fancy packages.


回答1:


You are actually creating a bar plot in the second example

The following will work

 # your variable
 fact <- as.factor(c('a','a','b'))
 # 
 b <- plot(fact)
 text(x=b,y=c(table(fact)), label = c(table(fact)),xpd=TRUE,col='blue')

You could wrap it as function plot.factor.

plot.factor <- function(x ,..., label=TRUE) { 

  cc <- table(x)
  b <- barplot(cc,...)
  if (label){
    text(x = b, y = c(cc), label = c(cc), xpd = TRUE, col = 'blue')
  } 
return(invisible(b))
}


# Then

plot(fact) 
# would produce the same result


来源:https://stackoverflow.com/questions/19417760/histogram-of-factor-with-labels-on-frequency-bars

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!