I a*_* am 34 plot r colors 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")
Run Code Online (Sandbox Code Playgroud)
现在,如果X的值> 0,那么该值应为绿色(在图中).如果Y的值> 0,则该值应为红色(在图中).
有人可以帮助我吗?
mne*_*nel 74
参数col将设置颜色,您可以将其与ifelse语句结合使用.有关?plot详细信息,请参阅
# using base plot
plot(x,y,xlab="PC1",ylab="PC2", col = ifelse(x < 0,'red','green'), pch = 19 )
Run Code Online (Sandbox Code Playgroud)

要做同样的事情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')
Run Code Online (Sandbox Code Playgroud)

或者,在 中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()
Run Code Online (Sandbox Code Playgroud)