2016-10-27 6 views
2

私は単純な問題があります。 ggplot2でヒストグラムをプロットする方法は、binwidthと固定し、虹色(または他のパレット)で塗りつぶしますか?ヒストグラムをカラーグラデーションで塗りつぶすにはどうすればいいですか?

私はそのようなデータを持っているとしましょう:

myData <- abs(rnorm(1000)) 

私は、ヒストグラムをプロットしたい、例えば使用binwidth=.1。それはしかし、データに応じて、ビンの数が異なる原因となります。

ggplot() + geom_histogram(aes(x = myData), binwidth=.1) 

enter image description here

私はビン(例えばn=15)の数を知っていたなら、私のようなものを使用したい:

ggplot() + geom_histogram(aes(x = myData), binwidth=.1, fill=rainbow(n)) 

をしかし、私はこの単純な問題に悩まされています。

+0

正しく理解すれば、ヒストグラムの各ビンを虹色のグラデーションに従って色分けする必要がありますか? –

+0

はい、まさに私が望むものです – Art

+0

@ user20650私はこの答えを見ましたが、そこにはビンの数が固定されていますので、私の問題を解決できません。 – Art

答えて

4

あなたが本当にビンの数が柔軟たい場合は、ここで私の小さな問題を回避するには、次のとおりです。

library(ggplot2) 

gg_b <- ggplot_build(
    ggplot() + geom_histogram(aes(x = myData), binwidth=.1) 
) 

nu_bins <- dim(gg_b$data[[1]])[1] 

ggplot() + geom_histogram(aes(x = myData), binwidth=.1, fill = rainbow(nu_bins)) 

enter image description here

+0

まさに私が必要とするものです。私はちょうどそれを行うためのいくつかのより簡単な方法があると思って(そして望んでいた):)ありがとう! – Art

0

ビン幅が固定されている場合は、ここでは内部関数を使用している代替ソリューションですggplot2:::bin_breaks_width()の前にのグラフを作成する前に、ビン数を取得してください。それはまだこの問題を回避するだがthe other solutionのように二回geom_histogram()を呼び出すために回避:第3の選択肢として

# create sample data 
set.seed(1L) 
myData <- abs(rnorm(1000)) 
binwidth <- 0.1 

# create plot  
library(ggplot2) # CRAN version 2.2.1 used 
n_bins <- length(ggplot2:::bin_breaks_width(range(myData), width = binwidth)$breaks) - 1L 
ggplot() + geom_histogram(aes(x = myData), binwidth = binwidth, fill = rainbow(n_bins)) 

enter image description here


、集約はggplot2の外で行うことができます。次いで、geom_col()カムgeom_histogram()の代わりに使用する:breaks連続x軸を維持する代わりに、levels(myData2)のx軸上にプロットされ

# start binning on multiple of binwidth 
start_bin <- binwidth * floor(min(myData)/binwidth) 
# compute breaks and bin the data 
breaks <- seq(start_bin, max(myData) + binwidth, by = binwidth) 
myData2 <- cut(sort(myData), breaks = breaks, by = binwidth) 

ggplot() + geom_col(aes(x = head(breaks, -1L), 
         y = as.integer(table(myData2)), 
         fill = levels(myData2))) + 
    ylab("count") + xlab("myData") 

enter image description here

留意されたいです。そうでなければ、各因子ラベルがプロットされ、x軸が乱雑になる。 rainbow()の代わりに組み込みのggplot2カラーパレットが使用されていることにも注意してください。

関連する問題