Web上でデータの可視化ができるPlotlyをRで試してみる

この記事は『R Advent Calendar 2013』12日目の記事です。

Plotlyとは?

https://plot.ly/
plotly | Analyze and visualize data, together

Plotlyはオンライン上でデータの可視化できるWebサービスです。
作成したグラフをブラウザ上で確認したり、ズームイン・ズームアウトが可能です。

有名ドコロですと、ワシントン・ポストが採用したことがあるそうですね。
Do low taxes on the rich leave the middle-class with lower wages?

あとは、Mashableとか。
How Do NBA Superstars Stack Up on Social Media? You Decide


Plotlyには嬉しい事に、様々な言語のAPIが用意されているので、自分の好きな環境で試すことが可能です。

対応言語

今回はRで試してみましょう。
なお、無料版ですとAPIを叩けるのが1日50回までなので注意が必要です。
無料版は非公開ファイルが50個まで、総ファイル数が150個までだそうです。

インストール

公式ページに詳しく書いてあるので、その通りに実行すればOKです。
devtoolsを使ってGithubからインストールする方法と、
tar.gzからインストールする方法が可能なようです。
今回はgithubからインストールしてみましょう。

> install.packages("devtools")
> library("devtools")
> devtools::install_github("plotly/R-api")

登録

Plotlyを使うためにはユーザー登録が必要です。
公式ページから各方法で登録後、usernameとAPIkeyを取得します。

> library(plotly)
> p <- plotly(username="ksmzn", key=api_key)

pにPlotlyClassが入り、p$plot, p$style, p$layoutの3つのメソッドが使用可能になります。

判別分析の結果を載っけてみる

それでは、実際にグラフ描画してみます。
お題は、みんな大好きirisデータで判別分析です。
判別分析部分のコードは、
フリーソフトによるデータ解析・マイニングからお借りしました。

グラフ

拡大・縮小や、つかんで移動したり、ダブルクリックで戻るといった操作ができます。

コード
library(MASS)
even.n<-2*(1:75)-1
train.data<-iris[even.n,]
test.data<-iris[-even.n,]
Iris.lab<-factor(c(rep("S",25),rep("C",25),rep("V",25)))
train.data[,5]<-Iris.lab
train.data[c(1,26,51),]
(Z<- lda(Species~ .,data=train.data))
Y<-predict(Z,test.data)

# Plotly
xc<-as.matrix(Y$x[,1][Y$class=="C"])
yc<-as.matrix(Y$x[,2][Y$class=="C"])
xs<-as.matrix(Y$x[,1][Y$class=="S"])
ys<-as.matrix(Y$x[,2][Y$class=="S"])
xv<-as.matrix(Y$x[,1][Y$class=="V"])
yv<-as.matrix(Y$x[,2][Y$class=="V"])

data = list(x=x0, 
            y=y0, 
            type = 'scatter',
            mode = 'markers');


data.s = list(
  name="setosa",
  x=xs, 
  y=ys, 
  marker = list(
    symbol = 'circle',
    color = 'red'
  ),
  type = 'scatter',
  mode = 'markers');

data.c = list(
  name="versicolor",
  x=xc, 
  y=yc, 
  marker = list(
    symbol = 'cross',
    color ='blue'
  ),
  type = 'scatter',
  mode = 'markers');

data.v = list(
  name="virginica",
  x=xv, 
  y=yv, 
  marker = list(
    symbol = 'square',
    color = 'green'
  ),
  type = 'scatter',
  mode = 'markers');

layout = list(
  "title"= "irisの判別分析",
  "xaxis"= list(
    "title"="LD1"
    ),
  "yaxis"= list(
    "title"="LD2"
  )
)

response = p$plotly(list(data.s,data.c,data.v), kwargs=list(layout=layout))
url = response$url
filename = response$filename

url にグラフのURLが入ります。今回の場合は https://plot.ly/~ksmzn/5/ でした。
例えばhttps://plot.ly/~ksmzn/5/600/600/のように、
https://plot.ly/~ksmzn/5/[width]/[height]/ とすることで、グラフの大きさを指定することができるので、ブログなどにiframeで埋め込むときに便利です。

公式サンプルの紹介

公式ページにいろいろとサンプルがあるので、
いくつか転載してみます。

Line and Scatter Plot


ヒートマップ


というわけで、Plotlyを使うことでインタラクティブなグラフ作成が可能になりました。
シェアも気軽ですし、なにより簡単にWebページに埋め込めるのが嬉しいですね。

PythonやJuliaにも対応しているので、iPython notebookやiJuliaと組み合わせてつかうと面白いかもしれません。
特にJuliaは、まだ定番の可視化ライブラリが決まってないようですし。

以上、『R Advent Calendar 2013』12日目の記事でした。