2017-04-26 42 views
0

我想做一個2d的情節,其中盒/瓷磚根據輸入數據框的列進行標記。我以前使用過geom_bin2d(和stat_bin2d)做類似的事情,但它似乎只允許計數或密度爲實際繪製的材質。示例代碼是這樣的:使用geom_bin2d與ggplot2的自定義標籤

df <- data.frame(Year = c(rep(2010, 4), rep(2011, 4), rep(2012, 4)), Rank = rep(1:4, 3), 
       Diff = c(rep(0, 3), 1, 0, -1, 2, 0, -3, rep(0, 3))) 


ggplot(df, aes(Year, Rank, Diff)) + 
    geom_bin2d() + 
    scale_fill_gradient(low='gray', high='red') 

我想要的是類似的東西,但與指導欄也對應的框中顯示的數據。注意我爲了說明的目的而手動添加這些數字。任何幫助?

enter image description here

回答

2

有沒有必要斌在這裏,因爲(如果我明白你的問題)你想在其他兩個變量來表示格點繪製一個變量的值。

ggplot(df, aes(factor(Year), factor(Rank), fill=Diff)) + 
    geom_tile(height=0.8, width=0.8) + 
    geom_text(aes(label=Diff)) + 
    scale_fill_gradient(low='gray', high='red') + 
    coord_equal() + 
    labs(x="Year", y="Rank") + 
    theme_classic() 

enter image description here

+0

這確實解決了!這裏使用'fill'似乎是缺失的環節。 –