2013-08-21 4 views
3

어떻게이 ggplot2와누적 히스토그램은

x <- runif(100,0,10) 
h <- hist(x) 
h[["counts"]] <- cumsum(h[["counts"]]) 
plot(h) 

같은 누적 히스토그램을 얻을 수 있을까?

나는 누적 히스토그램을 사용 geom_histogram()을 다음 ycumsum(..count..)를 사용하려면이

lines(h[["breaks"]],c(0,h[["counts"]])) 

+0

어떻게 이미지로 플롯을 추가하는 방법에 대한 : 그래서 당신이 편리한 함수와 다른 다각형을 만들 수 있습니까? – ziggystar

+0

내 대답은 아래에 복제를 쐈어. ''theme_bw()''또는''theme_classic()''를 사용하면 더 가까이서 볼 수 있습니다. – PatrickT

답변

10

같은 다각형을 그리 싶다. 누적 선은 stat_bin()geom="line"y 값을 cumsum(..count..)으로 계산하여 계산할 수 있습니다. base R hist의 모습을 재현하기 위해 geom_line에 데이터 :

ggplot(NULL,aes(x))+geom_histogram(aes(y=cumsum(..count..)))+ 
     stat_bin(aes(y=cumsum(..count..)),geom="line",color="green") 

enter image description here

+0

질문에있는 것과 같은 다각형을 그릴 수 있습니까? –

+0

너무 빨리 답변 해 주셔서 감사합니다.하지만 이것이 내가 필요한 것만은 아닙니다. 질문에서 다각형을주의 깊게 관찰하면 각 세그먼트는 가운데가 아니라 막대의 오른쪽 상단에서 끝납니다. –

+1

누군가가 그 마법의 ..count ..가 어디서 왔는지 궁금하다면 여기를 참고하십시오 : http://stackoverflow.com/questions/14570293/special-variables-in-ggplot-count-density-etc – Mischa

1

건물 디드의 대답에, 여기에 ggplot2 (해들리 저자)를 얻을 수있는 방법입니다.

간략한 설명 :베이스 R과 같은 방식으로 저장소를 가져 오려면 binwidth=1boundary=0을 설정합니다. 비슷한 모양을 얻으려면 color=blackfill=white을 사용했습니다. 그리고 선분의 동일한 위치를 얻으려면 ggplot_build을 사용했습니다. 이 속임수를 사용하는 다른 답변을 Didzis에서 찾을 수 있습니다.

# make a dataframe for ggplot 
set.seed(1) 
x = runif(100, 0, 10) 
y = cumsum(x) 
df <- data.frame(x = sort(x), y = y) 

# make geom_histogram 
p <- ggplot(data = df, aes(x = x)) + 
    geom_histogram(aes(y = cumsum(..count..)), binwidth = 1, boundary = 0, 
       color = "black", fill = "white") 

# extract ggplot data 
d <- ggplot_build(p)$data[[1]] 

# make a data.frame for geom_line and geom_point 
# add (0,0) to mimick base-R plots 
df2 <- data.frame(x = c(0, d$xmax), y = c(0, d$y)) 

# combine plots: note that geom_line and geom_point use the new data in df2 
p + geom_line(data = df2, aes(x = x, y = y), 
     color = "darkblue", size = 1) + 
    geom_point(data = df2, aes(x = x, y = y), 
     color = "darkred", size = 1) + 
    ylab("Frequency") + 
    scale_x_continuous(breaks = seq(0, 10, 2)) 

# save for posterity 
ggsave("ggplot-histogram-cumulative-2.png") 

마음이 편할 수도 있습니다. ggplot 객체는 최소값과 최대 값인 x의 두 값을 저장합니다.

# Make polygons: takes a plot object, returns a data.frame 
get_hist <- function(p, pos = 2) { 
    d <- ggplot_build(p)$data[[1]] 
    if (pos == 1) { x = d$xmin; y = d$y; } 
    if (pos == 2) { x = d$x; y = d$y; } 
    if (pos == 3) { x = c(0, d$xmax); y = c(0, d$y); } 
    data.frame(x = x, y = y) 
} 
df2 = get_hist(p, pos = 3) # play around with pos=1, pos=2, pos=3 

enter image description here enter image description here enter image description here

+0

나는 그 질문을 알고 있습니다. 4 살 이었지만이 일을 할 길을 찾고 있었고 나 자신을 해결해 냈습니다. 저에게 약간의 노력이 필요 했으므로 여기서 공유 할 생각이었습니다. – PatrickT