如何在R中调整LISA聚类图例顺序:High-High居首,Insignificant居末
调整R中LISA聚类图例顺序的解决方案
要实现将“high-high”置于图例顶端、“insignificant”置于末尾的需求,只需调整legend()函数中图例文本和对应颜色的顺序,确保两者一一匹配即可。修改后的代码如下:
quadrant <- vector(mode="numeric",length=nrow(local)) # centers the variable of interest around its mean m.qualification <- OA.Census$Qualification - mean(OA.Census$Qualification) # centers the local Moran's around the mean m.local <- local[,1] - mean(local[,1]) # significance threshold signif <- 0.1 # builds a data quadrant quadrant[m.qualification >0 & m.local>0] <- 4 quadrant[m.qualification <0 & m.local<0] <- 1 quadrant[m.qualification <0 & m.local>0] <- 2 quadrant[m.qualification >0 & m.local<0] <- 3 quadrant[local[,5]>signif] <- 0 # plot in r brks <- c(0,1,2,3,4) colors <- c("white","blue",rgb(0,0,1,alpha=0.4),rgb(1,0,0,alpha=0.4),"red") plot(OA.Census,border="lightgray",col=colors[findInterval(quadrant,brks,all.inside=FALSE)]) box() # 调整图例顺序:high-high 放顶端,insignificant 放末尾 legend("bottomleft", legend = c("high-high","low-low","low-high","high-low","insignificant"), fill = c("red","blue",rgb(0,0,1,alpha=0.4),rgb(1,0,0,alpha=0.4),"white"), bty="n")
关键修改说明:
- 调整
legend参数的文本顺序为c("high-high","low-low","low-high","high-low","insignificant"),直接匹配你需要的展示顺序。 - 同步调整
fill颜色向量为c("red","blue",rgb(0,0,1,alpha=0.4),rgb(1,0,0,alpha=0.4),"white"),保证每个图例文本和绘图中实际颜色完全对应:- "high-high"对应红色(原
colors[5]) - "low-low"对应蓝色(原
colors[2]) - "low-high"对应半透明蓝色(原
colors[3]) - "high-low"对应半透明红色(原
colors[4]) - "insignificant"对应白色(原
colors[1])
- "high-high"对应红色(原
- 绘图核心逻辑无需改动,因为
quadrant数值与颜色的映射关系保持不变,仅调整了图例的展示顺序。
内容的提问来源于stack exchange,提问作者user19729000
相关产品推荐
相关产品推荐

