【发布时间】:2012-08-04 00:20:26
【问题描述】:
我想根据值绘制不同颜色的图表。我写了下面的代码,
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,则该值应为红色(在图中)。
有人可以帮我吗?
【问题讨论】:
我想根据值绘制不同颜色的图表。我写了下面的代码,
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,则该值应为红色(在图中)。
有人可以帮我吗?
【问题讨论】:
参数col 将设置颜色,您可以将它与ifelse 语句结合使用。详情请见?plot。
# using base plot
plot(x,y,xlab="PC1",ylab="PC2", col = ifelse(x < 0,'red','green'), pch = 19 )
在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')
【讨论】:
ifelse 语句应该可以做到这一点。例如` col = ifelse(x>1&y>1,'red', ifelse(x2,'green','grey'))`