基于 R 中的值使用条件颜色绘图 [英] Plot with conditional colors based on values in R
本文介绍了基于 R 中的值使用条件颜色绘图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想根据值绘制具有不同颜色的图形.我写了下面的代码,
I want to plot a graph with different colors based on values. I wrote the below code,
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,则该值应为红色(在图中).
Now, if the value of X is >0, then that value should be in green (in the graph). if the value of Y is >0, then that value should be in red (in the graph).
有人可以帮我吗?
推荐答案
参数 col
将设置颜色,您可以将其与 ifelse
语句结合使用.有关详细信息,请参阅 ?plot
.
The argument col
will set the colours, you could use this in conjunction with an ifelse
statement. See ?plot
for more details.
# using base plot
plot(x,y,xlab="PC1",ylab="PC2", col = ifelse(x < 0,'red','green'), pch = 19 )
在 ggplot2
中做同样的事情.
To do the same thing in 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')
这篇关于基于 R 中的值使用条件颜色绘图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文