简体   繁体   中英

How to remove the zero labels in Histogram plot in R?

Any tips to remove the zero labels in between the histogram bars?

在此处输入图片说明

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

How about this?

# 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

A slightly different answer using the labeling in hist instead of adding text afterwards.

You do not provide your data, so I will use some data that is handy to illustrate.

The labels argument can specify the individual 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)

固定标签

Thanks @Daniel Anderson, it Ok now (Thumbs Up)

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

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM