gpt4 book ai didi

R ggplot2 : colouring step plot depending on value

转载 作者:行者123 更新时间:2023-12-04 12:33:39 25 4
gpt4 key购买 nike

如何配置 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))

最佳答案

aes中需要group = 1:

# 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

关于R ggplot2 : colouring step plot depending on value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8737454/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com