Vary colors of axis labels in R based on another variable

后端 未结 4 937
青春惊慌失措
青春惊慌失措 2020-12-09 11:33

I usually use ggplot2, but in this case I am using the regular image() function to plot a heatmap of a large data set. I can label all the labels as re

4条回答
  •  遥遥无期
    2020-12-09 11:49

    I like very much thelatemail's approach, and can only add a small refinement since the fixed "at" positions (as in the example above with at = 1:3) didn't work well for me. In my case, I needed to generate a barplot and provided my own values for space and width parameters. In the end what I used looks like (example with random data in which I wanted the bars and labels for positive (non-negative, to be more precise) data values to be green and red otherwise. For this example I also use the letters function to provide labels and rotate the labels using las = 2):

    x <- rnorm(26)
    color <- rep("green", length(x))
    color[x < 0] <- "red"
    
    par(mar=c(6,4.1,4.1,2.1))
    barplot(x, las = 2, ylim = c(min(x)-0.5, max(x)+0.5), col = color, space = 0.5, width = 2)    
    Map(function(x,y,z) 
    axis(1,at=x,col.axis=y,labels=z,lwd=0,las=2),
    seq(from = 2, by = 3, length.out = length(x)),
    color,
    letters
    )
    axis(1,at=seq(from = 2, by = 3, length.out = length(x)),labels=FALSE)
    

提交回复
热议问题