在R中使用向量进行条件Barchart着色 [英] Conditional Barchart coloring with a vector in R
问题描述
我正在尝试创建一个带有负值和正值的简单条形图,并将我的输入作为矢量.我希望条形图以红色显示正值,以蓝色显示负值.我知道这个问题很简单,但似乎无法解决.
I am attempting to create a simple barplot with both negative and positive values with my input as a vector. I would like the barplot to display the positive values colored in red and the negative values colored in blue. I understand this problem is simple, but I cannot seem to figure it out.
这是我的载体:
x <- (1.9230769, 1.2961538, 0.2576923, -1.5500000, -1.3192308,
0.2192308, 1.8346154, 1.6038462, 2.5653846, 4.1423077)
我尝试了以下代码:
barplot(x, ylim=c(-8,8), if(x>0) {col="red"} else {col="blue"})
但是我不断收到错误消息
but I keep getting an error that says
在if(x> 0){时:条件的长度> 1,并且只有第一个元素将被使用"
"In if (x > 0) { : the condition has length > 1 and only the first element will be used"
如何理解整个矢量并有条件地用红色和蓝色绘制它?
How can I get it to understand to run through the entire vector and plot it conditionally with red and blue?
谢谢
亚当
推荐答案
使用
barplot(x, ylim=c(-8,8), col=ifelse(x>0,"red","blue"))
col =
需要一个长度与 x
相同的向量(否则它将循环使用值).而且,您实际上不能有条件地指定类似的参数.与仅运行一次的 if
不同, ifelse
将使向量成为所需的对象.
col=
expects a vector with the same length as x
(or it will recycle values). And you can't really conditionally specify parameters like that. The ifelse
will make the vector as desired unlike if
which only runs once.
这篇关于在R中使用向量进行条件Barchart着色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!