2016-12-07 19 views
1

私はビンの内容とグラデーションの両方を表示している個々のビンで2Dヒストグラムを作成しようとしています。データは、両方の軸で0〜4(唯一)の範囲の整数です。ggplotでstat_bin2dのカウントと軸のラベル

私はthis answerで作業しましたが、いくつかの問題があります。まず、いくつかのビンが、グラデーションを一切持たないことになります。以下のMWEでは、130と60の左下のビンが空白に見えます。第2に、ビンは両方の軸において0より下にシフトされる。この軸の問題については、xとyの両方に0.5を単に追加できることがわかりました。しかし、最後には、軸ラベルをビン内の中央に配置したいと思い、0.5がそれに対処していないと付け加えます。

library(ggplot2) 

# Construct the data to be plotted 
x <- c(rep(0,190),rep(1,50),rep(2,10),rep(3,40)) 
y <- c(rep(0,130),rep(1,80),rep(2,30),rep(3,10),rep(4,40)) 
data <- data.frame(x,y) 

# Taken from the example 
ggplot(data, aes(x = x, y = y)) + 
    geom_bin2d(binwidth=1) + 
    stat_bin2d(geom = "text", aes(label = ..count..), binwidth=1) + 
    scale_fill_gradient(low = "snow3", high = "red", trans = "log10") + 
    xlim(-1, 5) + 
    ylim(-1, 5) + 
    coord_equal() 

enter image description here

は、私は色のグラデーションと軸ラベルの両方で間違ってやっている明白なものはありますか?私はまた、他のパッケージ/コマンドでそれを行うより良い方法があれば、ggplotまたはstat_bin2dと結婚していません。前もって感謝します!

答えて

1

stat_bin2dは、cut関数を使用してビンを作成します。デフォルトでは、cutは、左側に開いていて右側に閉じているビンを作成します。 stat_bin2dinclude.lowest=TRUEも設定し、最も低い間隔も左に閉じます。私はstat_bin2dのコードを調べて、間違っているものを正確に把握しようとしていませんが、それはのcutがどのように選択されているかと関係しているようです。いずれにしても、ビン区切りを明示的に-1で開始するように設定することで、望ましい動作を得ることができます。たとえば、次のように

ggplot(data, aes(x = x, y = y)) + 
    geom_bin2d(breaks=c(-1:4)) + 
    stat_bin2d(geom = "text", aes(label = ..count..), breaks=c(-1:4)) + 
    scale_fill_gradient(low = "snow3", high = "red", trans = "log10") + 
    xlim(-1, 5) + 
    ylim(-1, 5) + 
    coord_equal() 

enter image description here

半整数値にブレークを設定し、整数格子点上のタイルを中央に:

ggplot(data, aes(x = x, y = y)) + 
    geom_bin2d(breaks=seq(-0.5,4.5,1)) + 
    stat_bin2d(geom = "text", aes(label = ..count..), breaks=seq(-0.5,4.5,1)) + 
    scale_fill_gradient(low = "snow3", high = "red", trans = "log10") + 
    scale_x_continuous(breaks=0:4, limits=c(-0.5,4.5)) + 
    scale_y_continuous(breaks=0:4, limits=c(-0.5,4.5)) + 
    coord_equal() 

enter image description here

または、強調します値が離散的である場合、ビンを単位幅の半分に設定します。

ggplot(data, aes(x = x, y = y)) + 
    geom_bin2d(breaks=seq(-0.25,4.25,0.5)) + 
    stat_bin2d(geom = "text", aes(label = ..count..), breaks=seq(-0.25,4.25,0.5)) + 
    scale_fill_gradient(low = "snow3", high = "red", trans = "log10") + 
    scale_x_continuous(breaks=0:4, limits=c(-0.25,4.25)) + 
    scale_y_continuous(breaks=0:4, limits=c(-0.25,4.25)) + 
    coord_equal() 

enter image description here

+0

パーフェクト!これは非常に有益です。ほんとうにありがとう。乾杯! –

関連する問題