Search code examples
rrchartsslidify

rChart. adding additional labels in scatterChart


I have a problem in adding labels in ?nPlot(). For example:

```{r nvd3plot, echo=FALSE,results='asis'}
set.seed(9485)
dat<- data.frame(Gene_Name= LETTERS[1:15], Value1= sample(-8:20,15,replace=TRUE),Value2=sample(-6:10,15,replace=TRUE),stringsAsFactors=FALSE) 
library(rCharts)
r1<- nPlot(Value1~Value2,data=dat, type="scatterChart")
r1$show('inline')
```

Right now, it displays the values on each point. I would like to also include "Gene_Name" along with the values. Any help will be appreciated as I have a presentation tomorrow. Thanks.


Solution

  • Here is how to do it with rCharts. The key is to use the chart method and pass a javascript function to tooltipContent. It accepts four arguments, of which we will be using the e argument that provides access to the actual data points. So e.point.Gene_Name accesses the Gene_Name for each point. You can view a demo of this chart on rcharts viewer

    dat<- data.frame(
      Gene_Name= LETTERS[1:15], 
      Value1 = sample(-8:20, 15, replace = TRUE),
      Value2 = sample(-6:10, 15, replace = TRUE)
    )
    
    library(rCharts)
    r1<- nPlot(Value1~Value2,data=dat, type="scatterChart")
    r1$chart(tooltipContent = "#! function(key, x, y, e){
      return '<b>Gene Name</b>: ' + e.point.Gene_Name
    } !#")
    r1
    

    NOTE. You need the #! and !# tags to indicate to rCharts that the value is a JS literal. This will ensure that it passes it as a JS literal and not as a string while converting the payload to json.