You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

  1. 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.
  2. Count 100-values: sum(data == 100) gives us the number of data points equal to 100 (in your dataset, that's 10 points).
  3. Base histogram with neutral color: We use light gray for the base bars so the red highlight pops clearly.
  4. Add the red highlight: The rect() function draws a red rectangle over the 95-100 bin:
    • xleft/xright match the bin's 95-100 range
    • ybottom starts at the top of the non-100 values (total bin count minus 100-count: 16-10=6)
    • ytop extends to the full height of the bin (16)
    • border=NA removes 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 03:11:47