使用基于R中的值的条件颜色绘图

时间:2012-08-07 01:49:01

标签: r colors plot ggplot2

我想根据值绘制不同颜色的图形。我写了下面的代码,

np_graph <- data.frame(C1 = -5:5, C2 = -5:5)
x=np_graph2$C1
y=np_graph2$C2
plot(x,y,xlab="PC1",ylab="PC2")

现在,如果X的值> 0,那么该值应为绿色(在图中)。如果Y的值> 0,则该值应为红色(在图中)。

有人可以帮助我吗?

2 个答案:

答案 0 :(得分:69)

参数col将设置颜色,您可以将其与ifelse语句结合使用。有关详细信息,请参阅?plot

# using base plot
plot(x,y,xlab="PC1",ylab="PC2", col = ifelse(x < 0,'red','green'), pch = 19 )

enter image description here

ggplot2中做同样的事情。

#using ggplot2
library(ggplot2)
ggplot(np_graph) + geom_point(aes(x = C1, y = C2, colour = C1 >0)) +
  scale_colour_manual(name = 'PC1 > 0', values = setNames(c('red','green'),c(T, F))) +
  xlab('PC1') + ylab('PC2')

enter image description here

答案 1 :(得分:3)

或者,在ggplot2中,您可以基于ifelse语句设置新列“颜色”,然后使用scale_color_identity将这些颜色应用于图形:

np_graph %>% mutate(Color = ifelse(C1 > 0, "green", "red")) %>%
  ggplot(aes(x = C1, y= C2, color = Color))+
  geom_point()+
  scale_color_identity()

enter image description here