AnkP
AnkP

Reputation: 651

Add color legend based on values in a column in R

This may be a very basic plotting question, but I am unable to resolve it even after reading many posts. I created a basic plot for this data-

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
        .
.

. .

The data has around 100columns and 20000 rows. There are 14 unique categories in the 2nd column ie mal_mito, PF3D7_01, PF3D7_02, PF3D7_03 ...etc and I am coloring values in plots based on these.

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

I am trying to add a color legend in this plot showing which color corresponds to which 2nd column value. I end up with a pdf file with line plots for all the columns with 3 plots per page. I tried using image.plot but I am not able to get it right. Thanks!

enter image description here

Upvotes: 1

Views: 2610

Answers (2)

Sandipan Dey
Sandipan Dey

Reputation: 23129

Update your code to add legend at the bottom:

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

Upvotes: 0

Vlo
Vlo

Reputation: 3188

Use legend(); see example

# 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

Upvotes: 1

Related Questions