更改为多边形图的颜色并添加图例

时间:2019-03-04 14:24:59

标签: r plot colors range polygon

关注Assign colours to values and plot horizontal bars in R中的问题

使用所有数据值,如何更改为以下代码,以便切换hmin2条形上的颜色。该行的左侧应为蓝色,右侧应为红色。

FullRange = range(dataframe123, na.rm=TRUE)

BoxRanges = lapply(dataframe123, range, na.rm=TRUE)


plot(NULL, xlim=FullRange, ylim=c(0,3),  yaxt="n", xlab="Value", ylab="")
abline(v=19.293)
axis(2, at=(0:2)+0.4, labels=c("hmin1", "hmin2","hmin3"), 
lty=0, las=2)

for(i in 1:3) {
polygon(c(BoxRanges[[i]][1], BoxRanges[[i]][1], 19.293, 19.293), 
    c(i-1,i-0.2,i-0.2,i-1), col="red")
polygon(c(19.293, 19.293, BoxRanges[[i]][2], BoxRanges[[i]][2]), 
    c(i-1,i-0.2,i-0.2,i-1), col="blue")
}

此外,我如何在图例中添加说明颜色的图例?

红色代表参数的负变化,蓝色代表参数的正变化。

enter image description here

被困了几个小时。任何帮助将不胜感激,谢谢。

1 个答案:

答案 0 :(得分:1)

可以在循环外为polygon添加hmin2的一个选项。为了添加图例,您应该增加绘图区域(xlimylim),以便图例可见。

plot(NULL, xlim=c(FullRange[1]-1, FullRange[2] +1), ylim=c(-1,4),  yaxt="n", xlab="Value", ylab="")
abline(v=19.293)
axis(2, at=(0:2)+0.4, labels=c("hmin1", "hmin2","hmin3"), 
     lty=0, las=2)

for(i in c(1,3)) {
  polygon(c(BoxRanges[[i]][1], BoxRanges[[i]][1], 19.293, 19.293), 
          c(i-1,i-0.2,i-0.2,i-1), col="red")
  polygon(c(19.293, 19.293, BoxRanges[[i]][2], BoxRanges[[i]][2]), 
          c(i-1,i-0.2,i-0.2,i-1), col="blue")
}
i = 2
polygon(c(BoxRanges[[i]][1], BoxRanges[[i]][1], 19.293, 19.293), 
        c(i-1,i-0.2,i-0.2,i-1), col="blue")
polygon(c(19.293, 19.293, BoxRanges[[i]][2], BoxRanges[[i]][2]), 
        c(i-1,i-0.2,i-0.2,i-1), col="red")

legend(x = 20, y = 4.5, legend = "negative changes",
     border = NULL, fill = "red",
     bty = "n",
     bg = "n")
legend(x = 20, y = 4, legend = "positive changes",
       border = NULL, fill = "blue",
       bty = "n",
       bg = "n")

enter image description here

编辑

如果要在绘图中添加标题,则必须在main中使用plot。要将标签添加到行中,可以使用text

plot(NULL, xlim=c(FullRange[1]-1, FullRange[2] +1), ylim=c(-1,4),  yaxt="n", xlab="Value", ylab="", main = "Range of H min values with parameter changes")
abline(v=19.293)
axis(2, at=(0:2)+0.4, labels=c("hmin1", "hmin2","hmin3"), 
     lty=0, las=2)

for(i in c(1,3)) {
  polygon(c(BoxRanges[[i]][1], BoxRanges[[i]][1], 19.293, 19.293), 
          c(i-1,i-0.2,i-0.2,i-1), col="red")
  polygon(c(19.293, 19.293, BoxRanges[[i]][2], BoxRanges[[i]][2]), 
          c(i-1,i-0.2,i-0.2,i-1), col="blue")
}
i = 2
polygon(c(BoxRanges[[i]][1], BoxRanges[[i]][1], 19.293, 19.293), 
        c(i-1,i-0.2,i-0.2,i-1), col="blue")
polygon(c(19.293, 19.293, BoxRanges[[i]][2], BoxRanges[[i]][2]), 
        c(i-1,i-0.2,i-0.2,i-1), col="red")

legend(x = 20, y = 4.5, legend = "negative changes",
       border = NULL, fill = "red",
       bty = "n",
       bg = "n")
legend(x = 20, y = 4, legend = "positive changes",
       border = NULL, fill = "blue",
       bty = "n",
       bg = "n")
text(x = 17.5, y = -0.9, labels ="19.293", col = "black", cex = 0.9)