I am using geom_boxplot
to draw candlesticks using stock market data. The problem is that the individual boxplot's upper and lower edges as well as the upper whisker end point show up way higher on the y-axis than their corresponding values. The relative height (difference between upper and lower edges) and the end point of the lower whisker of each boxplot are fine though. Here's my code :
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
}
Here's 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
Am I doing something wrong here?
Could not completely understand your problem but this seems to work nicely:
http://www.perdomocore.com/2012/using-ggplot-to-make-candlestick-charts-alpha/
Thank you FXQuantTrader for introducing a beautiful and fast alternative approach to the candlestick bars in R! Awesome, concise, easy to read! Here comes a bit improved version of FXQuantTrader's solution, which include:
- wraps it into a function
- supports lower resolution (down to 1 sec bars)
- changes candle's whiskers colour from black to proper one
- adds small horizontal line for bars with Close == Open
- adds 3rd colour (blue) to bars with Close == Open
- adds 'alpha' argument which allows you to make the whole candlesticks chart more transparent, so when you draw on top some Bollinger Bands and/or Moving Averages the bars will be less distracting (more like a background)
- a bit more comments for newbies to figure out what is going on :)
Here she comes:
There are more efficient ways to create OHLC candlesticks with
ggplot2
than the way you have described usinggeom_boxplot
. Your code seems very similar to the example in the link: http://www.perdomocore.com/2012/using-ggplot-to-make-candlestick-charts-alpha/It seems many people are putting ggplot candlestick examples on the net that are based on the example in that link using
geom_boxplot
. But the problem with plotting withgeom_boxplot
is that the plotting itself gets slow at producing plots as the number of bars plotted increases.Here is one computationally faster solution for plotting financial data using candlesticks/OHLC bars: