如何删除R中直方图中的零标签?

时间:2018-01-22 18:16:31

标签: r histogram

有关删除直方图条之间零标签的提示吗?

enter image description here

hist(links$Survey_Duration, breaks = seq(0,50,5), main = "Survey Duration",
     labels = TRUE, border = "black",
     xlab = "Survey", ylim = c(0, 15), col = "gray", las = 1, xaxt='n')

axis(side=1, at=seq(0,50,5), labels=seq(0,50,5))

abline(v = mean(links$Survey_Duration), col = "royalblue", lwd = 1.5)

abline(v = median(links$Survey_Duration), col = "red", lwd = 1.5)

legend(x = "topright", c("Mean", "Median"), col = c("royalblue","red"),
       lwd = c(1.5,1.5))

3 个答案:

答案 0 :(得分:5)

这个怎么样?

# modify data so there's zero in one of the bins
mtcars$mpg <- ifelse(mtcars$mpg >= 25 & mtcars$mpg <= 30, NA, mtcars$mpg)

# save plot parameters
h <- hist(mtcars$mpg, plot = FALSE)

# produce plot
plot(h, ylim = c(0, 14))

# add labels manually, recoding zeros to nothing
text(h$mids, h$counts + 1, ifelse(h$counts == 0, "", h$counts))

hist_no_zero

答案 1 :(得分:1)

使用hist中的标签而不是之后添加文字的答案略有不同。

您不提供数据,因此我将使用一些便于说明的数据。

labels参数可以指定单个标签

H1 = hist(iris$Sepal.Length, breaks = 3:8, plot=FALSE)
BarLabels = H1$counts
BarLabels[BarLabels == 0] = ""
hist(iris$Sepal.Length, breaks = 3:8, labels = BarLabels)

Fixed Labels

答案 2 :(得分:0)

谢谢@Daniel Anderson,现在好了(竖起大拇指)

links$Survey_Duration <- ifelse(links$Survey_Duration > 15 &
                                links$Survey_Duration <= 25, 
                                NA, 
                                links$Survey_Duration)

h <- hist(links$Survey_Duration, breaks = seq(0,50,5), plot = FALSE)

plot(h, ylim = c(0, 14), main = "Survey Duration", xlab = "Time", col = "gray", las = 1)

text(h$mids, h$counts + 1, ifelse(h$counts == 0, "", h$counts))

axis(side=1, at=seq(0,50,5), labels=seq(0,50,5))

abline(v = mean(links$Survey_Duration), col = "royalblue", lwd = 1.5)

abline(v = median(links$Survey_Duration), col = "red", lwd = 1.5)

legend(x = "topright", 
       c("Mean", "Median"), 
       col = c("royalblue","red"),
       lwd = c(1.5,1.5))

enter image description here