Question: (Closed) R Plot: Plotting range of negative and positive values in different color
0
Anushka20 wrote:

Hello all,

This could be a trivial query but I am very new to R. I have data in two columns (Col X and ColY). Column X has ONLY positive values while Column Y has both positive and negative values. I would like to plot X vs Y, but with certain given ranges of negative and positive values of Y, in different colors. For example my data is like:

X              Y

5.89558    5.79116
4.83266    2.66533
5.21103    1.42206
3.83974    -7.67948
4.47855    -8.95710
4.66096    -3.32192
9.77715    -2.03952
8.17131    -5.11321
4.86396    -1.72792

I would like to plot value of negative subset of Y ranging from (< 0 to -4) in one color (say red) and the subset positive values of Y ranging between (>0 to 4) in green. And rest of the values in Grey.

I would really appreciate help in defining conditional subset  in R and plotting them in different colors.

Thanks

R • 17k views
modified 4.9 years ago by pristanna570 • written 4.9 years ago by Anushka20

Hello Anki!

We believe that this post does not fit the main topic of this site.

What andrew.j.skelton73 said. However, the general idea is `col=ifelse(Y<0, "blue", "red")`.

For this reason we have closed your question. This allows us to keep the site focused on the topics that the community can help with.

If you disagree please tell us why in a reply below, we'll be happy to talk about it.

Cheers!

2
andrew.j.skelton735.9k wrote:

This post will probably be taken down due to it's lack of relation to bioinformatics. I'd suggest posting this in StackOverflow. Also, make your long term R less painful in terms of plots by learning ggplot2.

I  will be careful in future and I apologies for this.  I will definitely work on it to improve my knowledge.Thanks

1
pristanna570 wrote:

There is a nice post about subsetting in R: http://www.ats.ucla.edu/stat/r/faq/subset_R.htm

And there is how you can do it:

```set=read.table("input.txt")
subset1 <- subset(set, V2 > -4 & V2 <= 0)
subset2 <- subset(set, V2 > 0 & V2 < 4)
plot(set, col="grey", ylim=c(-10,10), xlim=c(0,10))
par(new=T)
plot(subset1, col="red", ylim=c(-10,10), xlim=c(0,10))
par(new=T)
plot(subset2, col="green", ylim=c(-10,10), xlim=c(0,10))```

This solution is overly complicated. Just supply a vector of colors to col= and be done with it. This allows arbitrarily complex color schemes without plotting large number of subsets again and again.

Or, of course, one could just use ggplot2 and have it do everything.