2014-12-15 4 views
6

필자는 ggplots 'stat_bin2d'계층을 사용하여 생성 할 수있는 플로트와 본질적으로 동일한 줄을 만들고 싶지만, 변수에 매핑되는 개수 대신 빈과 관련된 개수를 레이블로 표시하고 싶습니다. 각 빈. stat_bin2d()를 사용하여 ggplot2에서 카운트 라벨을 계산하는 방법은 무엇입니까?

나는 각 빈에 대한 카운트가 명확하게 표시되어 another thread

data <- data.frame(x = rnorm(1000), y = rnorm(1000)) 

ggplot(data, aes(x = x)) + 
    stat_bin() + 
    stat_bin(geom="text", aes(label=..count..), vjust=-1.5) 

에서 해당 1D 문제에 대한 다음과 같은 솔루션을 얻었다. 그러나 1D에서 2D로 이동하면이 작업은 수행됩니다.

ggplot(data, aes(x = x, y = y)) + 
    stat_bin2d() 

그러나 오류가 발생합니다.

ggplot(data, aes(x = x, y = y)) + 
    stat_bin2d() + 
    stat_bin2d(geom="text", aes(label=..count..)) 

Error: geom_text requires the following missing aesthetics: x, y 
+3

A [재현성 예]를 작성하는 시간을 갖고 (http://stackoverflow.com/questions/5963269/how-to-make-a -great-r-reproducible-example)을 샘플 입력으로 사용하면 데이터가 어떻게 보이는지 분명합니다. 지금까지 시도를 보여주십시오. 어디서 붙어 있는지 정확히 설명하십시오. – MrFlick

+1

사과, 나는 뜻하지 않았을 때 실수로 게시했습니다. 업데이트했습니다! – user4009949

+0

내가 찾은 마지막 코멘트는 [Hadley in 2010] (https://groups.google.com/forum/#!topic/ggplot2/6lx_mYJVf3w)에서 기본적으로'stat_bin2d'를 사용할 수 없다고 말합니다. 당신은 당신 자신의 요약을해야 할 것이다. – MrFlick

답변

3

실수로 내 질문에 답변했습니다.

library(ggplot2) 
data <- data.frame(x = rnorm(1000), y = rnorm(1000)) 
x_t<-as.character(round(data$x,.1)) 
y_t<-as.character(round(data$y,.1)) 
x_x<-as.character(seq(-3,3),1) 
y_y<-as.character(seq(-3,3),1) 
data<-cbind(data,x_t,y_t) 



ggplot(data, aes(x = x_t, y = y_t)) + 
    geom_bin2d() + 
    stat_bin2d(geom="text", aes(label=..count..))+ 
    scale_x_discrete(limits =x_x) + 
    scale_y_discrete(limits=y_y) 

을 그래서 당신이가는 : 난 당신이 텍스트 번호에서 당신이 비닝하는 변수를 변환 할 때 stat_bin2d 그래서, 작동합니다 알아 냈어. 불행히도 binwidth를 ggplot() 외부로 설정해야 이상적인 해결책이되지 않습니다. 변수를 텍스트로 변환 할 때 왜 작동하는지 모르겠지만 거기에 있습니다.

+1

이 문자 변환을 수행 할 필요는 없습니다. 아마도 이것은이 답변이 원래 게시되었을 때 적절한 해결책 이었지만 더 최신 버전의'ggplot'에서는 필요하지 않습니다. 내 대답을 보라. – Andrie

+0

좋아요! 나는 그들이 일하는 것을 기쁘게 생각합니다. ggplot() 외부의 Binning은 세상 끝이 아니었지만 ggplot() 내에서 훨씬 더 편리했습니다. – SeldomSeenSlim

5

ggplot의 최신 버전에서 이것은 완벽하게 가능하며 오류없이 작동합니다.

stat_bin2d()을 호출 할 때 동일한 인수를 사용해야합니다. 예를 들어, 두 라인 binwidth = 1을 설정

library(ggplot2) 
data <- data.frame(x = rnorm(1000), y = rnorm(1000)) 

ggplot(data, aes(x = x, y = y)) + 
    geom_bin2d(binwidth = 1) + 
    stat_bin2d(geom = "text", aes(label = ..count..), binwidth = 1) + 
    scale_fill_gradient(low = "white", high = "red") + 
    xlim(-4, 4) + 
    ylim(-4, 4) + 
    coord_equal() 

enter image description here

관련 문제