The Nightman
The Nightman

Reputation: 5759

Color points if ID in vector in ggplot2

I have imported data in this form:

Sample1 Sample2 Identity
1    2    chr11-50-T
3    4    chr11-200-A
v <- read.table("myfile", header = TRUE)

I have a vector that looks like this:

x <- c(50,100)

And without some other aesthetic stuff I am plotting column 1 vs column 2 labeled with column 3.

p <- ggplot(v, aes(x=sample1, y=sample2, alpha=0.5, label=identity)) +
geom_point() +
geom_text_repel(aes(label=ifelse(sample2>0.007 |sample1>0.007 ,as.character(identity),''))) + 

I would like to somehow indicate those points that contain a number in their ID, found within the vector x. I was thinking this could be done with color, but it doesn't really matter to me as long as there is a difference between the two types of points.

So for instance if the points containing a number in x were to be colored red, the first point would be red because it has 50 in the ID and the second point would not be, because 200 is not a value in x.

Upvotes: 1

Views: 442

Answers (2)

user3640617
user3640617

Reputation: 1576

I came up with the following solution:

vafs<-read.table(text="Sample1 Sample2 Identity
       1    2    chr11-50-T
       3    4    chr11-200-A", header=T)

vec <- c(50,100)

vafs$vec<- sapply(vafs$Identity, FUN=function(x) 
ifelse(length(grep(pattern=paste(vec,collapse="|"), x))>0,1,0))

vafs$vec <- as.factor(vafs$vec)

ggplot(vafs, aes(x=Sample1, y=Sample2, label=Identity, col=vec),alpha=0.5)+geom_point()

Upvotes: 1

Mike H.
Mike H.

Reputation: 14370

You could add in a TRUE/FALSE value as a column and use that as a color. I had to remove your label = ... aes since that's not an aes in ggplot2. Also everything is transparent because you use aes(alpha = 0.5):

library(ggrepel)
library(ggplot2)

vafs$col <- grepl(paste0(x,collapse = "|"), vafs$Identity)

p <- ggplot(vafs, aes(x=Sample1, y=Sample2, alpha=0.5, color = col)) +
  geom_point() +
  geom_text_repel(aes(label=ifelse(Sample2>0.007 |Sample1>0.007 ,as.character(Identity),'')))

enter image description here

Upvotes: 1

Related Questions