In an R barplot, I can color a selected bar; e.g., with code like the following:
data <- c(3,4,2,1)
colors <- rep("#ffffff", 4)
colors[2] <- "#ff0000"
barplot(data, col=colors, space=c(0,0,0,0))
Question: How can I color only a specified rightmost x% of a selected bar, for 0<x<100?
E.g., coloring only the rightmost 70% of the 2nd bar in the above example would look about like this:
(I expected there to be an already-answered question about this, or something like it -- but if there is any, I haven't been able to find it. My apologies if I've missed it.)
CodePudding user response:
You have to add a rectangle to the barplot:
out <- barplot(data, col="white", space=c(0,0,0,0))
out
# [,1]
# [1,] 0.5
# [2,] 1.5
# [3,] 2.5
# [4,] 3.5
You have 4 bars and out
lists the center on the x-axis for each one. You want to shade part of the second bar, from (2 - .7) to 2 on the x-axis and from 0 to data[2]
or 4 on the y-axis:
rect((2 - .7), 0, 2, 4, border=NA, col="red")
rect(1, 0, 2, 4, border="black") # Optional to overprint the border