Skipper Lin
Skipper Lin

Reputation: 75

Plot a horizontal line in chartSeries Error in get.current.chob() : improperly set or missing graphics device

I want to create a time-series plot for Goldman adjusted stock price since 2000 and draw a horizontal line for the mean price. However, I reached "Error in get.current.chob() : improperly set or missing graphics device" error message when I tried to draw the horizontal line.

library(quantmod)
getSymbols("GS", from = "2000-01-01", src="yahoo")
chart_Series(GS[,6], name = "Goldman Sachs", TA = 'addLines(h = mean(GS[,6]))')

Upvotes: 1

Views: 372

Answers (1)

phiver
phiver

Reputation: 23598

You are mixing codes from 2 different charting options. You have chartSeries in quantmod and chart_Series. A bit confusing as the second version tends to have to nicer charts, but is not complete like chartSeries. There is no add_Lines function for chart_Series. But there are workarounds.

Simple solution, use chartSeries:

library(quantmod)
getSymbols("GS", from = "2000-01-01", src="yahoo")
chartSeries(GS[,6], name = "Goldman Sachs", TA = 'addLines(h = mean(GS[,6]))')

Bit more complicated using chart_Series:

You need to use add_TA, which needs a xts object so first you need to create an xts object with the same value. Those are the first 3 lines of code below. Next you plot the data and then you use add_TA to add the horizontal line. And you need to tell add_TA where to plot the line (on = 1 means main plot window).

dates <- index(GS)
gs_mean <- mean(GS[,6])
gs_mean_xts <- xts(rep(gs_mean, length(dates)), dates)

# create chart
chart_Series(GS[,6], name = "Goldman Sachs")

# plot horizontal line on plot
add_TA(gs_mean_xts, on = 1, col = "blue", lwd = 2)

Upvotes: 1

Related Questions