问题
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