Skip to content

Instantly share code, notes, and snippets.

@nitaku
Last active August 29, 2015 14:24
Show Gist options
  • Save nitaku/0e36dcc66487cd0997c1 to your computer and use it in GitHub Desktop.
Save nitaku/0e36dcc66487cd0997c1 to your computer and use it in GitHub Desktop.
R template

A base template for WebVis gists supporting R plots in SVG. The R script produces a random bar chart, logs the generated data (echoed to the JavaScript console) and writes the plot to an SVG device.

Thanks to d3.js, the produced SVG is loaded into the DOM, rather than included as an external image. This allows both scripting and styling (demonstrated by the use of CSS to render the bars with crisp edges).

#surface1 path {
shape-rendering: crispEdges;
}
<?php
$LOG = json_encode(shell_exec('Rscript main.R'));
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>R template</title>
<script src="http://d3js.org/d3.v3.min.js"></script>
<style>
html, body { padding: 0; margin: 0; }
</style>
<link type="text/css" href="index.css" rel="stylesheet"/>
</head>
<body>
<script>
var __log = <?= $LOG; ?>;
if (__log)
console.log(__log);
d3.xml('output.svg', function(error, documentFragment) {
if (error) { throw error; }
svg_dom = documentFragment
.getElementsByTagName('svg')[0];
d3.select('body').node().appendChild(svg_dom);
svg_d3 = d3.select(container).select('svg');
svg_d3
.attr('width', '960px')
.attr('height', '500px');
});
</script>
</body>
</html>
svg('output.svg', width=9.6, height=5)
counts <- round(runif(9,0,10))
sprintf('Random vector is: [%s]', paste(counts, collapse=','))
barplot(counts,
main = 'Bogus data',
horiz = TRUE)
invisible(dev.off())
Display the source blob
Display the rendered blob
Raw
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment