基于R中的值绘制条件颜色 [英] Plot with conditional colors based on values in R

查看:465
本文介绍了基于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 将设置颜色, code> 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 中执行相同的操作。

#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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆