R ggplot2:着色步骤图取决于值

时间:2012-01-05 03:55:46

标签: r ggplot2

如何配置ggplot2步骤图,以便当绘制的值超过某个级别时,它是一种颜色,当它低于某一级别时,它是另一种颜色? (最后我想指定使用的颜色。)

我的第一个想法是,这将是一个简单的问题,只需要我在现有数据框中添加一列,并将此列映射到geom_step()的aes()。这是有用的:我得到两种颜色,但它们重叠,如下图所示: geom_step() plot with overlapping colours

过去几个小时我搜索过SO,发现了许多相似但不完全相同的问题。然而,尽管在不同的层中尝试了各种各样的组合,但我还是无法解决问题。代码如下。任何帮助非常感谢。

require(ggplot2)

tmp <- structure(list(date = structure(c(1325635200, 1325635800, 1325636400, 
1325637000, 1325637600, 1325638200, 1325638800, 1325639400, 1325640000, 
1325640600, 1325641200, 1325641800, 1325642400, 1325643000, 1325643600, 
1325644200, 1325647800, 1325648400, 1325649000, 1325649600, 1325650200, 
1325650800, 1325651400, 1325652000, 1325652600, 1325653200, 1325653800, 
1325654400, 1325655000, 1325655600, 1325656200, 1325656800), tzone = "", tclass = c("POSIXct", 
"POSIXt"), class = c("POSIXct", "POSIXt")), Close = c(739.07, 
739.86, 740.41, 741.21, 740.99, 741.69, 742.64, 741.34, 741.28, 
741.69, 741.6, 741.32, 741.95, 741.86, 741.02, 741.08, 742.08, 
742.88, 743.19, 743.18, 743.78, 743.65, 743.66, 742.78, 743.34, 
742.81, 743.31, 743.81, 742.91, 743.09, 742.47, 742.99)), .Names = c("date", 
"Close"), row.names = c(NA, -32L), class = "data.frame")
prevclose <- 743
tmp$status <- as.factor(ifelse (tmp$Close> prevclose, "Above", "Below"))

ggplot() +
    geom_step(data = tmp,aes(date, Close, colour = status))

1 个答案:

答案 0 :(得分:9)

group = 1中需要aes

# top panel
ggplot(tmp, aes(date, Close, colour = status, group = 1)) + 
  geom_step() + scale_colour_manual(values = c("pink", "green"))

也许你想做这样的事情:

# make sure that data is sorted by date
tmp2 <- arrange(tmp, date)

# add intermittent column between below/above
tmp3 <- tmp2[1, ]
for (i in seq(nrow(tmp2))[-1]) {
    if (tmp2[i-1, ]$status != tmp2[i, ]$status) {
        tmp3 <- rbind(tmp3,
                      transform(tmp2[i, ], Close = prevclose, status = tmp2[i-1, ]$status),
                      transform(tmp2[i, ], Close = prevclose))
    }
    tmp3 <- rbind(tmp3, tmp2[i, ])
}

# bottom panel
ggplot(tmp3, aes(date, Close, colour = status, group = 1)) + geom_step() +
  scale_colour_manual(values = c("pink", "green"))

enter image description here