【问题标题】:Histogram of factor with labels on frequency bars频率条上带有标签的因子直方图
【发布时间】:2013-10-25 09:56:24
【问题描述】:

如果我需要制作带有标签的直方图,我通常会使用hist(rnorm(100),labels=TRUE)。但是,如果我的数据是因素,那么我需要使用plot(as.factor(c("a","a","b")))。这个问题是labels=TRUE 不能与plot 一起使用; 我该如何解决这个问题

我最好想要一个不需要加载花哨的包的解决方案。

【问题讨论】:

    标签: r plot histogram


    【解决方案1】:

    您实际上是在第二个示例中创建条形图

    以下将起作用

     # 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')
    

    你可以把它包装成函数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
    

    【讨论】:

      猜你喜欢
      • 2014-03-05
      • 2020-01-27
      • 1970-01-01
      • 1970-01-01
      • 2015-04-26
      • 2014-10-22
      • 2017-07-17
      • 2020-03-28
      相关资源
      最近更新 更多