LoginSignup
4
4

More than 5 years have passed since last update.

ggplot2でdata.tableから二次元の集計表を作成してヒートマップとして表示

Last updated at Posted at 2014-07-15

はじめに

メモです。
data.tableからこういうのを作りたかったのです。
data.frameだったら、reshape2でやればいいのですが、data.tableのままでやるには以下のようにします。

やってみた

ライブラリの読み込み
library(data.table)
library(ggplot2)
library(reshape2)
表の読み込み
d <- fread(filename)
Var1とVar2の組み合わせをカウント
dat <- dcast.data.table(d, Var1 ~ Var2, fun=length)
dat2 <- melt(dat, id.vars = "Var1")
描画
g <- ggplot(dat2, aes(as.factor(Var1), variable, group=variable)) +
    geom_tile(aes(fill = value)) + 
    geom_text(aes(fill = dat2$value, label = round(dat2$value, 1)), size=2) +
    scale_fill_gradient(low = "white", high = "red")

print(g)

d, dat, dat2はいずれもdata.tableオブジェクトです。

参考

4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4