【问题标题】:Add color legend based on values in a column in R根据 R 中的列中的值添加颜色图例
【发布时间】:2016-09-15 18:11:14
【问题描述】:

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

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 行。第 2 列中有 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 但我无法正确使用它。谢谢!

【问题讨论】:

    标签: r plot colors


    【解决方案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)
    

    【讨论】:

    • 感谢 Vlo,我能够得到情节,但情节中的颜色类别现在超过 14 个,我需要仅针对第二列中唯一类别的颜色。无论如何也可以将其转换回线/直方图样式图。类型 ="h" 现在似乎不起作用。
    【解决方案2】:

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

    #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)  
    

    【讨论】:

    • 这很完美!非常感谢。现在将图例添加到图的末尾,因为我有大约 100 列,当我将其输出为 pdf 时,它出现在最后一页。无论如何要在每一页上绘制这个?我需要打破循环对吗?
    猜你喜欢
    • 1970-01-01
    • 2018-07-19
    • 2015-04-05
    • 2013-09-20
    • 2019-08-06
    • 1970-01-01
    • 1970-01-01
    • 2020-04-04
    • 2018-06-11
    相关资源
    最近更新 更多