首页 > 解决方案 > Color selected parts of data in basic R plot

问题描述

I am trying to plot a trend as datapoints over the years. I have added two regression lines with different colours that signify fitting for before and after an effect takes place. Now I would like to color my data points that correspond to the respective trend line but unfortunately, I have no idea on how to do it...

First I tried:

plot(as.numeric(colnames(df)[6:27]), unlist(df[56, 6:27]),  type = "o", col = "blue" )

but then realized that I also needed error bars, so I went with:

plot(df$x, df$y,
     ylim=range(c(df$y- sdev, df$y+ sdev)),
     pch=19, xlab="name1", ylab="name2",
     main="Title here")

and added the colored trend line with:

abline(name, col= "red")

Now, I know those are the same functions, but I could for the life of me not figure out how to restrict color to a certain area. I tried:

plot(df$x, df$y,
     ylim=range(c(df$y- sdev, df$y+ sdev)),
     pch=19, xlab="name1", ylab="name2",
     main="Title here", col(df$y > 2011) = "blue")

(in my head "make it blue for all years bigger 2011") but that gave me:

Error: unexpected ')' in ")"

Using only col = "blue" at the end worked but that of course colored the whole data. Sorry for the base question but I am kinda new to R... Thanks a lot!

标签: r

解决方案


try using col=ifelse(df$y>2011, "blue", "red") or any other color combination you prefer. this way creates a color vector with the color that each point have to be.


推荐阅读