Reputation:
I'm trying to plot axis labels in different colors. Using this code:
handball <- c(1.8, 1.72, 1.7, 1.65, 1.78, 1.68, 1.85, 1.72, 1.78, 1.79, 1.64, 1.74, 1.82, 1.77, 1.80, 1.84, 1.83, 1.80, 1.90, 1.82, 1.69, 1.78, 1.70)
hist(handball, prob = TRUE, col = "grey", axes = FALSE, xlab = NULL, ylab = NULL, xlim = c(min(handball), max(handball)))
lines(density(handball), col = "blue", lwd = 2)
lines(density(handball, adjust = 2), lty = "dotted", col = "darkgreen", lwd = 2)
axis(side = 1, at = c(min(handball), quantile(handball, 1/4), median(handball), quantile(handball, 3/4), max(handball)), labels = c(min(handball), quantile(handball, 1/4), median(handball), quantile(handball, 3/4), max(handball)), col.axis = c("black", "black", "red", "black", "black"))
I get this error:
Error in axis(side = 1, at = c(min(handball), quantile(handball, 1/4), :
graphical parameter "col.axis" has the wrong length
What am I doing wrong?
Upvotes: 2
Views: 789
Reputation:
@lukeA pointed out in their comment that col.axis can only take one value. So I plotted two axes, one for each color:
axis(side = 1, at = c(median(handball)), labels = c(median(handball)), col.axis = "red")
axis(side = 1, at = c(min(handball), quantile(handball, 1/4), quantile(handball, 3/4), max(handball)), labels = c(min(handball), quantile(handball, 1/4), quantile(handball, 3/4), max(handball)))
Looks fine now:
Here is another solution using a custom function, which makes sense when you have a lot of colors, but with only two colors I found simply duplicating the axis code and deleting the unwanted values to be quicker and easier.
Upvotes: 1