I am creating a shiny application where I use the rCharts package, I have a problem with fixing labels above all the points of the graph.
library(rCharts)
a
for shiny + clickme see http://www.slideshare.net/nachocab/interactive-r-visualizations-using-shiny-and-clickme, but also be aware that rCharts can use custom templates as in http://mostlyconjecture.com/blog/ which can then easily be deployed using renderChart
or renderChart2
.
for the nvd3
labelling question, the answer gets complicated really quickly. We intend to standardize some of these rCharts
behaviors, but I'm not sure this will be one. However, this might get you started. To see it in a demo see here or as a live example.
library(rCharts)
age <- c(1:20)
tall <- seq(0.5, 1.90, length = 20)
name <- paste(letters[1:20], 1:20, sep = "")
df <- data.frame(age = age, tall = tall, name = name)
n1 <- nPlot(age ~ tall ,data = df, type = "scatterChart")
n1$xAxis(axisLabel = "the age")
n1$yAxis(axisLabel = "the tall", width = 50)
#assuming you don't want tooltips if you have labels
#change back to what you had if assumption incorrect
n1$chart(tooltipContent = NULL)
#grab template from
#https://github.com/ramnathv/rCharts/blob/master/inst/libraries/nvd3/layouts/chart.html
#modify to add callback on graph render
n1$setTemplate(script = sprintf("
<script type='text/javascript'>
$(document).ready(function(){
draw{{chartId}}()
});
function draw{{chartId}}(){
var opts = {{{ opts }}},
data = {{{ data }}}
if(!(opts.type==='pieChart' || opts.type==='sparklinePlus' || opts.type==='bulletChart')) {
var data = d3.nest()
.key(function(d){
//return opts.group === undefined ? 'main' : d[opts.group]
//instead of main would think a better default is opts.x
return opts.group === undefined ? opts.y : d[opts.group];
})
.entries(data);
}
if (opts.disabled != undefined){
data.map(function(d, i){
d.disabled = opts.disabled[i]
})
}
nv.addGraph(function() {
var chart = nv.models[opts.type]()
.width(opts.width)
.height(opts.height)
if (opts.type != 'bulletChart'){
chart
.x(function(d) { return d[opts.x] })
.y(function(d) { return d[opts.y] })
}
{{{ chart }}}
{{{ xAxis }}}
{{{ x2Axis }}}
{{{ yAxis }}}
d3.select('#' + opts.id)
.append('svg')
.datum(data)
.transition().duration(500)
.call(chart);
nv.utils.windowResize(chart.update);
return chart;
},%s);
};
</script>
"
,
#here is where you can type your labelling function
"
function(){
//for each circle or point that we have
// add a text label with information
d3.selectAll('.nv-group circle').each(function( ){
d3.select(d3.select(this).node().parentNode).append('text')
.datum( d3.select(this).data() )
.text( function(d) {
//you'll have access to data here so you can
//pick and choose
//as example just join all the info into one line
return Object.keys(d[0]).map(function( key ){
return( key + ':' + d[0][key] )
}).join()
})
.attr('x',d3.select(this).attr('cx'))
.attr('y',d3.select(this).attr('cy'))
.style('pointer-events','none')
})
}
"
))
n1