2016-10-16 5 views
1

매트릭스의 행에서 동일한 그래프에 정렬 된 막대 그래프를 플롯해야합니다. 다음 예제에서는 5 개의 누적 히스토그램을 플롯해야합니다. 그러나 hist 명령은 전체 행렬의 하나의 히스토그램을 그립니다. 사용할 수있는 해결 방법이 있습니까?동일한 그래프에서 정렬 된 막대 그래프 플로팅

미리 감사드립니다.

아르투로

x <- 10; y <- 10; g <- 5 
dat <- matrix(rnorm((x + y) * g), ncol = x + y) 
hist (dat) 
+0

각 행에 대해 개별 막대 점을 원하고 비교를 위해 수직으로 쌓기를 원하십니까? – shayaa

+0

맞습니다. 각 행에는 고유 한 y 축과 공유 된 x 축이 있어야합니다. – Arturo

답변

-1

이것은 내가 같은 차트에 두 히스토그램을 생산하기 위해 사용하고 접근이다.

열 x가 연속적인 var이고 y가 factor 변수 인 데이터 집합을 고려하십시오. 각 레벨은 하나의 히스토그램을 생성합니다. ggplot2를 사용하는 코드 예를 아래에서 찾으십시오.

OverlayedHist <- function(mData  , 
          featureVar , 
          grouper  , 
          mbinwidth , 
          mTitle  , 
          mxlab  , 
          mylab  , 
          mlegendTitle 
){ 

    # function name: OverlayedHist 
    #  purpose: To produce overlayed histograms against a grouping variable 
    #   Input: 
    #   mData: dataset object in data.table format 
    # featureVar: name of continuous variable to produce histogram 
    #  grouper: the grouping variable to produce the histogram 
    #  mbinwidth: binwidth (see ggplot2 parameters) 
    #  mTitle: Character to define title 
    #   mxlab: Character to define xlab name 
    #   mylab: Character to define ylab name 
    # mlegendTitle: Character to define legend title 

    library(data.table) 
    library(ggplot2) 
    library(plotly) 

    p <- ggplot(allDat, aes(eval(parse(text = featureVar)), fill = eval(parse(text = grouper)))) + 
    geom_histogram(alpha = 0.7, position = 'identity', binwidth = mbinwidth) + 
    scale_fill_manual(values=c("#377EB8","#E41A1C")) + 
    ggtitle(mTitle) + 
    xlab(mxlab) + ylab(mylab) + 
    guides(fill=guide_legend(title=mlegendTitle)) + theme(plot.title = element_text(size=10)) 


    return(ggplotly(p)) 

} 

이 정보가 도움이되기를 바랍니다.

건배! K.

+0

방법을 테스트하기 위해 일부 작동 코드를 게시 하시겠습니까? – Arturo

+0

위의 대화 형 플롯의보다 자세한 버전을 찾을 수 있습니다. – mammask

1

ggplot 쉽게 작성하십시오 (긴 양식 데이터가 필요합니다).

library(tidyr); library(dplyr); library(ggplot2) 

df <- dat %>% t() %>% as.data.frame() %>% gather(row) # chage data into a long format 
Breaks <- hist(dat, plot=F)$breaks      # get (or decide) breaks 

ggplot(df, aes(x = value, fill = row)) + geom_histogram(position = "stack", breaks = Breaks) 

enter image description here

[EDITED]
이 당신이 원하는 무엇인가?

## original 
ggplot(df, aes(x = value)) + 
    geom_histogram(breaks = Breaks) + 
    facet_wrap(~ row)   # make histogram par group. 

    ## modified 
ggplot(df, aes(x = value, fill = row)) +     # change fill colour 
    geom_histogram(breaks = Breaks) + 
    facet_wrap(~ row, ncol = 1) +       # bring graphs into line 
    # facet_wrap(~ row, ncol = 1, scales = "free_y") # if you don't want fixed scale 
    theme(strip.background = element_blank(), strip.text.x = element_blank()) # delete labels 

enter image description here

[EDITED2 : base_plot 방법]
자료 플롯 시간을 절약 할 수 있습니다.

## example data 
x <- 1500; y <- 1500; g <- 30 
set.seed(1); dat <- matrix(rnorm((x + y) * g), ncol = x + y) 

## decide breaks 
Breaks <- seq(-4.5, 4.5, 0.5) 

## change par() to draw multiple graphs 
par.old <- par(mar = c(0.1, 4.0, 0.1, 0.5), oma = c(4, 0, 0, 0), mfrow = c(nrow(dat), 1)) 

for(i in 1:nrow(dat)) { 
    hist(dat[,i], breaks = Breaks, xaxt = "n", xlab = "", main = "") 
# grid(NULL) 
    } 
par(new=T) 
hist(dat[,nrow(dat)], breaks = Breaks, main = "", yaxt = "n", 
    xlab = "x", ylab = "", border = NA)   # add x-axis 

par(par.old) 
+0

감사합니다.하지만 기고가 즉시 표시되도록 플롯에서 각 행을 분리해야합니다. – Arturo

+0

감사합니다. 이것은 내가 원하는 것에 가깝다. 이제 코드를 이해해야합니다. :-) – Arturo

+0

주석 처리 된 코드도 감사드립니다. 당신이 괜찮다면, 한가지 더 질문이 있습니다. 때로는 제공된 예제와 같이 5x20이 아닌 30x6000까지 배열을 플로팅해야합니다. 이 경우에는 절차가 오래 걸리는 것으로 나타났습니다. 색깔을 없애면 속도가 빨라질 수 있다고 생각했습니다. 이것이 가능할 것이라고 생각하십니까? – Arturo

관련 문제