3

I'm trying to add a regression line to a simple scatterplot using rCharts in a Shiny app, but I can't get it to work. The following code displays the graph just fine (sans regression line) if you remove the p$layer() call. With it, the graph's axes are hidden, and there is no line, although the points still display. What am I doing wrong?

Thanks for your help.

output$kplot = renderChart({

     # Create dependency on submit button.
     input$submit

     # Add point when submit button is clicked.
     dataset = isolate(rbind(dataset, c(input$add_x, input$add_y)))

     # Re-fit data.
     dataset$fit = lm(dataset$mpg ~ dataset$hp)$fitted.values

     # Calculate graph minimums and maximums
     xmin = max(min(dataset$hp) - 10, 0) # Cut threshold at zero.
     xmax = (max(dataset$hp) + 11) + (50 - ((max(dataset$hp) + 10) %% 50))
     ymin = 0
     ymax = (max(dataset$mpg) + 1) + (5 - ((max(dataset$mpg) + 5) %% 5))

     p = rPlot(mpg ~ hp, data=dataset, type="point")
     p$addParams(dom="kplot")
     p$guides(
        x = list(
           min = xmin,
           max = xmax,
           numticks = xmax / 50 + 1,
           title = "HP"
        ),
        y = list(
           min = ymin,
           max = ymax,
           numticks = ymax / 5 + 1,
           title = "MPG"
        )
     )
     p$layer(y=dataset$fit, copy_layer=T, type="line", color=list(const="red"))
     return(p)
  })
kendaop
  • 107
  • 2
  • 13

1 Answers1

2

Please check the code below which I copied from @ramnathv's github

https://gist.github.com/ramnathv/7576061

require(ggplot2)
require(rCharts)

dat = fortify(lm(mpg ~ wt, data = mtcars))
names(dat) = gsub('\\.', '_', names(dat))

p1 <- rPlot(mpg ~ wt, data = dat, type = 'point')
p1$layer(y = '_fitted', copy_layer = T, type = 'line',
  color = list(const = 'red'),
  tooltip = "function(item){return item._fitted}")
p1
BigDataScientist
  • 1,045
  • 5
  • 17
  • 37