Vary colors of axis labels in R based on another variable

后端 未结 4 943
青春惊慌失措
青春惊慌失措 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:53

    You could specify a vector with the colors you want to apply to the labels and then use a loop to get the labels colored with axis(). In the following example, I use a different color for each level of a dot chart.

    DF <- data.frame(habitat=c("Hab 1","Hab 2","Hab 3","Hab 4","Hab 5"), mean=c(0.53,0.28,0.30,0.35,0.39), color=colors()[c(24,257,26,504,652)])
    > DF
    habitat mean      color
    1   Hab 1 0.53      black
    2   Hab 2 0.28     green3
    3   Hab 3 0.30       blue
    4   Hab 4 0.35 orangered1
    5   Hab 5 0.39     yellow
    
    par(mar=c(7, 5, 4, 3))
    dotchart(DF[,2], xlim=c(0.2,0.6), col=as.character(DF$color), pch=16, lcolor="white", xlab=colnames(DF[2])) # Plot the points 
    for (j in 1:5){
    axis(side=2, at=j, col.axis=as.character(DF$color)[j], labels=DF$habitat[j], las=1) # Add habitat as labels, each with corresponding color, on the left margin
    } 
    

提交回复
热议问题