根据值绘制带有条件颜色的折线图 [英] Plot a line chart with conditional colors depending on values
问题描述
我想绘制折线图.根据值,它应该改变它的颜色.我发现的是:
I want to plot a line chart. Depending on values it should change its color. What I found is:
plot(sin(seq(from=1, to=10,by=0.1)),type="p",
col=ifelse(sin(seq(from=1, to=10,by=0.1))>0.5,"red","yellow"))
那行得通.但是,一旦我从 type="p" 更改为 type="l",条件着色就会消失.
That works. But as soon as I change from type="p" to type="l" the conditional colouring disappears.
这种行为是有意为之吗?
Is that behavior intended?
使用基本图形绘制不同颜色的功能线的解决方案是什么?
What is a solution with base graphics to plot a functional line with different colors?
推荐答案
使用 segments
而不是 lines
.
segments
函数只会添加到现有的绘图中.要创建具有正确轴和范围的空白图,首先使用 plot
和 type="n"
绘制无".
The segments
function will only add to an existing plot. To create a blank plot with the correct axes and limits, first use plot
with type="n"
to draw "nothing".
x0 <- seq(1, 10, 0.1)
colour <- ifelse(sin(seq(from=1, to=10,by=0.1))>0.5,"red","blue")
plot(x0, sin(x0), type="n")
segments(x0=x0, y0=sin(x0), x1=x0+0.1, y1=sin(x0+0.1), col=colour)
请参阅?segments
了解更多详情.
See ?segments
for more detail.
这篇关于根据值绘制带有条件颜色的折线图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!