geom_boxplot (R) 的股票烛台绘制问题

2023-12-23

我在用geom_boxplot使用股市数据绘制烛台。问题在于,各个箱线图的上边缘和下边缘以及上须线端点在 y 轴上显示的位置远高于其相应值。不过,每个箱线图下须线的相对高度(上边缘和下边缘之间的差异)和端点都很好。这是我的代码:

candlestickPlot <- function(x){

library("ggplot2")

# x is a data.frame with columns 'date','open','high','low','close'
x$candleLower <- pmin(x$open, x$close)
x$candleUpper <- pmax(x$open, x$close)
x$candleMiddle <- NA
x$fill <- "red"
x$fill[x$open < x$close] = "green"

# Draw the candlesticks
g <- ggplot(x, aes(x=date, lower=candleLower, middle=candleMiddle, upper=candleUpper, ymin=low, ymax=high)) 
g <- g + geom_boxplot(stat='identity', aes(group=date, fill=fill))
g 
}

这是 x :

    date     close volume  open  high   low
5 2013-12-30 25.82 3525026 27.30 27.76  25.7
4 2013-12-31 27.41 5487204 25.25 27.70 25.25
3 2014-01-02 30.70 7835374 29.25 31.24 29.21
2 2014-01-03 30.12 4577278 31.49 31.80 30.08
1 2014-01-06 30.65 4042724 30.89 31.88 30.37

我在这里做错了什么吗?


有更有效的方法来创建 OHLC 烛台ggplot2比你所描述的使用方式geom_boxplot。您的代码看起来与链接中的示例非常相似:http://www.perdomocore.com/2012/using-ggplot-to-make-candlestick-charts-alpha/ http://www.perdomocore.com/2012/using-ggplot-to-make-candlestick-charts-alpha/

似乎很多人都将 ggplot 烛台示例放在网上,这些示例基于该链接中的示例,使用geom_boxplot。但是绘图的问题是geom_boxplot问题是,随着绘制的条形数量的增加,绘图本身生成绘图的速度会变慢。

这是一种计算速度更快的解决方案,用于使用烛台/OHLC 条绘制财务数据:

library(ggplot2)
library(quantmod)
FOSL <- getSymbols("FOSL", from="2015-01-01", auto.assign=FALSE)
names(FOSL) <- gsub("^.+\\.","",names(FOSL))  # remove "FOSL." from column names

rng <- "2015-08"
FOSL <- FOSL[rng]
FOSL <- data.frame(Date=as.POSIXct(index(FOSL)), FOSL[,1:4])

FOSL$chg <- ifelse(Cl(FOSL) > Op(FOSL), "up", "dn")
FOSL$width <- as.numeric(periodicity(FOSL)[1])
FOSL$flat_bar <- FOSL[, "High"] == FOSL[, "Low"]

# Candle chart:
pl <- ggplot(FOSL, aes(x=Date))+
  geom_linerange(aes(ymin=Low, ymax=High)) +
  theme_bw() +
  labs(title="FOSL") +
  geom_rect(aes(xmin = Date - width/2 * 0.9, xmax = Date + width/2 * 0.9, ymin = pmin(Open, Close), ymax = pmax(Open, Close), fill = chg)) + guides(fill = FALSE, colour = FALSE) + scale_fill_manual(values = c("dn" = "darkred", "up" = "darkgreen"))

# Handle special case of drawing a flat bar where OHLC = Open:
if (any(FOSL$flat_bar)) pl <- pl + geom_segment(data = FOSL[FOSL$flat_bar,], aes(x = Date - width / 2 * 0.9, y = Close, yend = Close, xend = Date + width / 2 * 0.9))

print(pl)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

geom_boxplot (R) 的股票烛台绘制问题 的相关文章

随机推荐