gridSVGで散布図上の点のIdentification
gridSVG - Export grid graphics as SVG
gridSVGはgridライブラリによるグラフィックスをSVG形式で出力するためのライブラリ。ggplot2はgridを利用しているので、ggplot2の出力もSVGにできる。単に出力するだけでなくJavaScriptを埋め込むことができるので、インタラクティブな機能を実装できる。標準でもSVG出力はサポートしているが、プロットの構造は保持できないため、データに依存したインタラクティブ機能の実装が自動化できない。
散布図上の点をクリックするとその点の情報がalertで表示される例。Chromeで動く。Firefoxはuseタグの扱い(correspondingUseElement)が違うのでクロスブラウザ対策が必要。
library(ggplot2) library(gridSVG) library(grid) library(rjson) pdf(file=NULL, width=7, height=5) ggplot(iris, aes(Petal.Width, Petal.Length)) + geom_point(aes(colour=Species, size=Sepal.Width)) grid.script(paste("var x=", toJSON(iris$Petal.Width),";",sep="")) grid.script(paste("var y=", toJSON(iris$Petal.Length),";",sep="")) grid.script(" info = function(e){ id = e.target.correspondingUseElement.id; id = parseInt(id.replace('geom_point.points.1.','')); alert('Petal.Width='+x[id-1]+'\\nPetal.Length='+y[id-1]); } ") grid.gedit("geom_point.points", name="geom_point.points") grid.garnish("geom_point.points", onclick="info(evt)") grid.export("iris_plot.svg") dev.off()