根据R中列中的值添加颜色图例

时间:2016-09-15 18:11:14

标签: r plot colors

这可能是一个非常基本的绘图问题,但即使阅读了很多帖子后我也无法解决。我为这个数据创建了一个基本的图 -

ID  ID_chr  IVC10_BB_0048   IVC10_BB_0049 .......
mrna5.cds1  mal_mito_2  295.53  362.80
mrna4.cds1  mal_mito_3  297.33  359.69
mrna3.cds1  mal_mito_3  292.88  361.13
mrna2.cds1  mal_mito_4  298.19  360.76
mrna1.cds1  mal_mito_4  295.43  359.47
mrna5.cds1  mal_mito_5  429.18  520.89
mrna4.cds1  mal_mito    419.21  518.53
mrna3.cds1  mal_mito    431.56  527.69
mrna2.cds1  mal_mito    429.69  521.14
mrna1.cds1  mal_mito    423.87  509.44
mrna5.cds1  mal_mito    231.26  246.93
mrna4.cds1  mal_mito    206.76  231.48
mrna3.cds1  mal_mito    234.60  260.17
mrna2.cds1  mal_mito    230.75  254.36
mrna1.cds1  mal_mito    233.56  254.04
mrna5.cds8  PF3D7_01    5.745   8.022
mrna5.cds7  PF3D7_01    3.821   4.744
mrna5.cds6  PF3D7_01    3.847   4.794
mrna5.cds5  PF3D7_01    3.821   4.645
mrna5.cds4  PF3D7_02    5.542   7.004
mrna5.cds3  PF3D7_03    4.479   5.663
mrna5.cds2  PF3D7_04    4.252   5.266
        .
.

数据大约有100列和20000行。第二列中有14个独特的类别,即mal_mito,PF3D7_01,PF3D7_02,PF3D7_03 ......等等,我在基于这些的图中着色值。

IVC_all = read.table("input.txt")
pdf(file="test.pdf")
par(mfrow =c(3,1))
family <- as.factor(IVC_all[,1])
for ( i in seq(2,length( IVC_all ),1) ) plot(IVC_all[,i],ylab=names(IVC_all[i]),col=family,pch=19)
dev.off()

我试图在此图中添加一个颜色图例,显示哪个颜色对应于哪个第二列值。我最终得到一个pdf文件,其中所有列的线图都是每页3个图。我尝试使用image.plot,但我无法做到正确。谢谢!

enter image description here

2 个答案:

答案 0 :(得分:1)

使用legend();见例子

# Generate data
x = rnorm(1:10000)

# Default palette() only contains 8 colors. 
library(RColorBrewer)

# Plot, change `Spectral` to whatever you palette you want in `?brewer.pal`
plot(x, col = rep(brewer.pal(10, "Spectral"), each = 1000))

# Manually add legend, you need to set the x, y coordinates. `legend` args are the labels, so you need something like `unique(IVC_all[,1])`
legend(x = 1, y = 2, legend = c("hoho", "haha", paste(8:10)), col = brewer.pal(10, "Spectral"), lty = 1, cex = 1)

enter image description here

答案 1 :(得分:0)

更新您的代码以在底部添加图例:

#update
par(mfrow =c(4,1))
for ( i in seq(2,length( IVC_all ),1) )       
    plot(IVC_all[,i],ylab=names(IVC_all[i]),col=family,pch=19)
#add
unique.family <- unique(family)
plot(0, 0, type = "n", bty = "n", xaxt = "n", yaxt = "n")
legend("bottom", as.character(unique.family), 
        lwd=rep(2,length(unique.family)), 
        col=unique.family, horiz=TRUE)