如果我正確認識你,你可能沒有您的任何數據轉化爲矩陣,如果你願意使用geom_tile
從ggplot2
:
dat <- read.table(textConnection("Person,Messages
Dave,8
James,6
Dave,6
Dave,8
Dave,8
John,5
John,5
John,20
Dave,0"),sep = ",",header = TRUE)
dat <- ddply(dat,.(Person,Messages),summarise,val = length(Person))
ggplot(dat,aes(x = Messages, y = Person, fill = val)) +
geom_tile()
或者下面就來,你可以在image
用作輸入假設全矩陣有點費力的路線是我們在dat
開始與原始數據:
#Some data to pad with the missing combinations
pad <- expand.grid(unique(dat$Person),
min(dat$Messages):max(dat$Messages))
colnames(pad) <- c('Person','Messages')
#Aggregate the data and merge with pad data
dat <- ddply(dat,.(Person,Messages),summarise,val = length(Person))
tmp <- merge(dat,pad,all.y = TRUE)
#Convert from long to wide
rs <- cast(tmp,Person~Messages,value = 'val')
#Clean up the result
rownames(rs) <- rs$Person
rs <- rs[,-1]
rs[is.na(rs)] <- 0
> rs
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
Dave 1 0 0 0 0 0 1 0 3 0 0 0 0 0 0 0 0 0 0 0 0
James 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0
John 0 0 0 0 0 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1