Create legend in R with identical RGB color values as plot?

百般思念 提交于 2020-01-01 03:26:09

问题


I've created a simple scatter plot in R with specific RGB color values like this:

plot(shuffled, p_val, pch=19, col="black", xlim=c(0,100), ylim=c(0,1))
points(ri, p_val, pch=19, col=rgb(96,123,139, 50, maxColorValue=255), 
       xlim=c(0,100), ylim=c(0,1))
points(somo, p_val, pch=19, col=rgb(225,64,5, 50, maxColorValue=255), 
       xlim=c(0,100), ylim=c(0,1))

I would like to use the same color values in the code above to generate a figure legend. The code I am using looks like this, but I can't seem to figure out how to match the colors of the graph points.

legend("topright", c("Shuffled", "Riffled", "Somosome"), cex=1.0, bty="n", 
       c("black",col=rgb(96,123,139, 50, maxColorValue=255),col=rgb(225,64,5, 50, maxColorValue=255))

Can any one help? What is wrong with my legend? Thanks!


回答1:


This works for me:

plot(1:3,
    col=c("black",rgb(96,123,139, 50, maxColorValue=255),
               rgb(225,64,5, 50,maxColorValue=255)),pch=19)

legend("topright", c("Shuffled", "Riffled", "Somosome"), cex=1.0, bty="n",
   col=c("black",rgb(96,123,139, 50, maxColorValue=255),
      rgb(225,64,5, 50, maxColorValue=255)),pch=19)

Note you need to specify one vector of col=, the size of your labels, and you also have to have a pch= in there too. Alternatively you can do fill=[vector of colours] to draw filled boxes.




回答2:


The problem is that you are concatenating an R color keyword, "black", with hexadecimal color keys. Something like this should work:

colvec <- rgb(rbind(t(col2rgb("black")), ## this is obviously just 0, 0, 0
                    c(96,123,139),
                    c(225,64,5)),
              alpha=50,max=255)

plot(shuffled, p_val, pch=19, col=colvec[1], xlim=c(0,100), ylim=c(0,1))
points(ri, p_val, pch=19, col=colvec[2], 
       xlim=c(0,100), ylim=c(0,1))
points(somo, p_val, pch=19, col=colvec[3], 
       xlim=c(0,100), ylim=c(0,1))
legend("topright", c("Shuffled", "Riffled", "Somosome"), cex=1.0, bty="n",
       col=colvec)


来源:https://stackoverflow.com/questions/7948102/create-legend-in-r-with-identical-rgb-color-values-as-plot

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!