2013-10-17 61 views
1

通常,如果需要製作帶標籤的直方圖,我將使用hist(rnorm(100),labels=TRUE)。但是,如果我的數據是因素,那麼我需要使用plot(as.factor(c("a","a","b")))。與此相關的問題是labels=TRUE將不適用於plot; 我該如何解決這個問題帶頻標上標籤的因子直方圖

我最好想要一個解決方案,而不需要加載花哨的包。

回答

2

您實際上是創建在第二個例子中柱狀圖

下面的工作

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

enter image description here

你可以把它包裝成函數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 
+0

@agstudy確實.....和完成 – mnel