如何在R语言直方图中为最后一个区间内值为100的数据点着色
Highlight 100-Value Portion in the 95-100 Histogram Bin with Red
Got it, let's work through this together! You want to fill the part of the 95-100 bin that corresponds to the value 100 with red. Here's a straightforward solution using base R that builds on your existing code:
Full Modified Code
# Your original dataset data <- c(78,100,90,100,96,100,100,82,95,99,100,97,79,99,100,77,79,100,95,100,100,100,82,77,82) # Get histogram statistics without plotting first (to reuse bin dimensions) hist_stats <- hist(data, breaks = c(75,80,85,90,95,100), plot = FALSE) # Calculate how many data points are exactly 100 count_100 <- sum(data == 100) # Draw the base histogram with a neutral gray fill hist(data, xlab="Score", breaks=c(75,80,85,90,95,100), ylab = "Frequency", main = "Score Distribution", cex.main = 1.55, cex.lab = 1, freq = TRUE, col = "lightgray") # Overlay a red rectangle to highlight the 100-values in the 95-100 bin rect(xleft = 95, xright = 100, ybottom = hist_stats$counts[5] - count_100, ytop = hist_stats$counts[5], col = "red", border = NA)
Breakdown of the Changes
- Grab histogram stats first: Using
hist(plot=FALSE)lets us get the exact bin counts and ranges from your original plot, so we don't have to recalculate anything manually. - Count 100-values:
sum(data == 100)gives us the number of data points equal to 100 (in your dataset, that's 10 points). - Base histogram with neutral color: We use light gray for the base bars so the red highlight pops clearly.
- Add the red highlight: The
rect()function draws a red rectangle over the 95-100 bin:xleft/xrightmatch the bin's 95-100 rangeybottomstarts at the top of the non-100 values (total bin count minus 100-count: 16-10=6)ytopextends to the full height of the bin (16)border=NAremoves the rectangle's outline to make it blend seamlessly with the base histogram
This will give you the desired effect: the 95-100 bin has a gray lower section for values 95-99, and a red upper section for all the 100s.
内容的提问来源于stack exchange,提问作者Danny
相关产品推荐
相关产品推荐

