2013-03-22 133 views
2

我有一個基於GGPLOT2,熱圖呈現的某些因素的出現計數。但是,不同的數據集有時並不存在某些因素的實例,這意味着它們各自的熱圖看起來會有所不同。爲了使並排比較更容易,我想添加缺少的級別。不幸的是我沒有成功。添加缺少的因子水平的GGPLOT2熱圖

所以,我有一個看起來像這樣的數據:

> head(numRules) 
    Job Generation NumRules 
1 0   0  2 
2 0   1  1 
3 0   2  1 
4 0   3  1 
5 0   4  1 
6 0   5  1 
> levels(factor(numRules$NumRules)) 
[1] "1" "2" "3" 

我使用下面的代碼來渲染一個很好的熱圖計數每生成規則對所有崗位數量:

ggplot(subset(numRules, Generation < 21), aes(x=Generation, y=factor(NumRules))) + 
    stat_bin(aes(fill=..count..), geom="tile", binwidth=1, position="identity") + 
    ylab('Number of Rules') 

Heat map of count of number of rules by generation for all jobs

因此,熱圖說大多數時候運行只對特定的一代有一個單一的規則,但有時你會得到兩個,並在極少數情況下你會得到三個離子。

現在完全不同的集運行的可能實際上有一個給定的一代零條規則。但是,進行並排比較會有點令人困惑,因爲一張熱圖的y軸在[1,3]中有多個規則,而另一個可能在[0,2]中。我想要做的是標準化熱點圖表,以便他們所有都具有(0,1,2,3)中的因子級別,而不管規則的數量如何。例如,我想重新渲染上面的熱圖,即使在該特定數據框中沒有該圖的實例,也包括一個零規則的行。

我已經與包括設置休息和規模以及諸如此類的東西都沒有用各種咒語[R毆打這一點。我的直覺是有一個簡單的解決方案,但我無法找到它。

更新

如果我手動指定呼叫的水平factor我得到增加了對零個規則中的一行:

ggplot(subset(numRules, Generation < 21), aes(x=Generation, y=factor(NumRules,levels=c("0","1","2","3")))) + stat_bin(aes(fill=..count..), geom="tile", binwidth=1, position="identity") + ylab('Number of Rules')

其中產量this

不幸的是,你可以看到這個新行不正確着色。到達那裏!

回答

1

在這種情況會更容易改變你的數據。首先,閱讀你的數據。然後設置可變NumRules所有必要的電平(0〜3),以因子

numRules = read.table(text=" Job Generation NumRules 
1 0   0  2 
2 0   1  1 
3 0   2  1 
4 0   3  1 
5 0   4  1 
6 0   5  1", header=TRUE) 

numRules$NumRules = factor(numRules$NumRules, levels=c(0, 1, 2, 3)) 

現在計算次數的NumRules每個組合和Generation與功能table()存在於數據並將其保存到一些對象。

tab<-table(numRules$NumRules,numRules$Generation) 
tab 

    0 1 2 3 4 5 
    0 0 0 0 0 0 0 
    1 0 1 1 1 1 1 
    2 1 0 0 0 0 0 
    3 0 0 0 0 0 0 

從庫reshape2功能melt()使長格式的表格,並更改列名

library(reshape2) 
tab.long<-melt(tab) 
colnames(tab.long)<-c("NumRules","Generation","Count") 

疊加使用geom_tile()和設置fill=到包含實際數列與新數據幀中的數據。

ggplot(tab.long, aes(x=Generation, y=NumRules,fill=Count)) + 
    geom_tile() + 
    ylab('Number of Rules') 

enter image description here

+0

謝謝!這就是訣竅! – 2013-03-22 21:47:41

0

如果你有興趣的NumRules是因素的水平,那麼你可以通過只在指定scale_y_discrete()修復drop=FALSE此:

numRules = read.table(text=" Job Generation NumRules 
1 0   0  2 
2 0   1  1 
3 0   2  1 
4 0   3  1 
5 0   4  1 
6 0   5  1", header=TRUE) 

numRules$NumRules = factor(numRules$NumRules, levels=c(1, 2, 3)) 

ggplot(subset(numRules, Generation < 21), aes(x=Generation, y=NumRules)) + 
    scale_y_discrete(drop=FALSE) + 
    stat_bin(aes(fill=..count..), geom="tile", binwidth=1, position="identity") + 
    ylab('Number of Rules') 

結果:

all factors shown

+0

可悲的是,馬呂斯,整個行爲的水平「規則數」「3」也應該是深藍色的,而不是透明的。這幾乎是我現在所處的位置。 – 2013-03-22 06:26:54