programing

R에서 두 히스토그램을 함께 표시하는 방법은 무엇입니까?

showcode 2023. 6. 14. 21:58
반응형

R에서 두 히스토그램을 함께 표시하는 방법은 무엇입니까?

저는 R을 사용하고 있으며 당근과 오이 두 개의 데이터 프레임이 있습니다.각 데이터 프레임에는 측정된 모든 당근(총 100k 당근)과 오이(총 50k 오이)의 길이를 나열하는 단일 숫자 열이 있습니다.

당근 길이와 오이 길이의 두 히스토그램을 같은 그래프에 표시하려고 합니다.겹쳐서 투명성도 필요할 것 같습니다.또한 각 그룹의 인스턴스 수가 다르기 때문에 절대 수가 아닌 상대 주파수를 사용해야 합니다.

이런 것도 좋지만 두 개의 테이블에서 만드는 방법을 이해할 수 없습니다.

overlapped density

다음은 기본 그래픽과 알파 혼합(일부 그래픽 장치에서 작동하지 않음)을 사용하는 훨씬 더 간단한 솔루션입니다.

set.seed(42)
p1 <- hist(rnorm(500,4))                     # centered at 4
p2 <- hist(rnorm(500,6))                     # centered at 6
plot( p1, col=rgb(0,0,1,1/4), xlim=c(0,10))  # first histogram
plot( p2, col=rgb(1,0,0,1/4), xlim=c(0,10), add=T)  # second

핵심은 색상이 반투명하다는 것입니다.

편집, 2년 이상 경과:이것이 방금 투표를 받았기 때문에, 나는 알파 블렌딩이 매우 유용하기 때문에 코드가 생성하는 것에 대한 시각을 추가할 수 있다고 생각합니다.

enter image description here

연결한 이미지는 히스토그램이 아니라 밀도 곡선을 위한 것입니다.

만약 당신이 ggplot을 읽고 있었다면, 아마도 당신이 놓치고 있는 유일한 것은 당신의 두 개의 데이터 프레임을 하나의 긴 하나로 결합하는 것일 것입니다.

자, 여러분이 가지고 있는 것과 같은 것으로 시작해 봅시다. 두 개의 서로 다른 데이터 세트를 결합합니다.

carrots <- data.frame(length = rnorm(100000, 6, 2))
cukes <- data.frame(length = rnorm(50000, 7, 2.5))

# Now, combine your two dataframes into one.  
# First make a new column in each that will be 
# a variable to identify where they came from later.
carrots$veg <- 'carrot'
cukes$veg <- 'cuke'

# and combine into your new data frame vegLengths
vegLengths <- rbind(carrots, cukes)

그런 다음 데이터가 이미 긴 형식인 경우에는 필요하지 않습니다. 그림을 만드는 데 한 줄만 있으면 됩니다.

ggplot(vegLengths, aes(length, fill = veg)) + geom_density(alpha = 0.2)

enter image description here

자, 만약 여러분이 정말 히스토그램을 원한다면, 다음과 같은 것들이 작동할 것입니다.기본 "스택" 인수에서 위치를 변경해야 합니다.데이터의 모양에 대한 개념이 없다면 이를 놓칠 수도 있습니다.높은 알파가 더 좋아 보입니다.밀도 히스토그램도 만들었습니다.쉽게 제거할 수 있습니다.y = ..density..다시 숫자로 되돌리기 위해서.

ggplot(vegLengths, aes(length, fill = veg)) + 
   geom_histogram(alpha = 0.5, aes(y = ..density..), position = 'identity')

enter image description here

추가적으로, 저는 모든 주장이 단순히 다음과 같을 수 있다는 더크의 질문에 대해 논평했습니다.histㅠㅠㅠㅠ 는 어떻게 을 할.저는 그것이 어떻게 이루어질 수 있는지 질문을 받았습니다.다음은 정확히 더크의 모습을 보여줍니다.

set.seed(42)
hist(rnorm(500,4), col=rgb(0,0,1,1/4), xlim=c(0,10))
hist(rnorm(500,6), col=rgb(1,0,0,1/4), xlim=c(0,10), add = TRUE)

여기 제가 쓴 함수가 중첩 히스토그램을 나타내기 위해 의사 투명도를 사용합니다.

plotOverlappingHist <- function(a, b, colors=c("white","gray20","gray50"),
                                breaks=NULL, xlim=NULL, ylim=NULL){

  ahist=NULL
  bhist=NULL

  if(!(is.null(breaks))){
    ahist=hist(a,breaks=breaks,plot=F)
    bhist=hist(b,breaks=breaks,plot=F)
  } else {
    ahist=hist(a,plot=F)
    bhist=hist(b,plot=F)

    dist = ahist$breaks[2]-ahist$breaks[1]
    breaks = seq(min(ahist$breaks,bhist$breaks),max(ahist$breaks,bhist$breaks),dist)

    ahist=hist(a,breaks=breaks,plot=F)
    bhist=hist(b,breaks=breaks,plot=F)
  }

  if(is.null(xlim)){
    xlim = c(min(ahist$breaks,bhist$breaks),max(ahist$breaks,bhist$breaks))
  }

  if(is.null(ylim)){
    ylim = c(0,max(ahist$counts,bhist$counts))
  }

  overlap = ahist
  for(i in 1:length(overlap$counts)){
    if(ahist$counts[i] > 0 & bhist$counts[i] > 0){
      overlap$counts[i] = min(ahist$counts[i],bhist$counts[i])
    } else {
      overlap$counts[i] = 0
    }
  }

  plot(ahist, xlim=xlim, ylim=ylim, col=colors[1])
  plot(bhist, xlim=xlim, ylim=ylim, col=colors[2], add=T)
  plot(overlap, xlim=xlim, ylim=ylim, col=colors[3], add=T)
}

투명 색상에 대한 R의 지원을 사용하여 수행하는 다른 방법은 다음과 같습니다.

a=rnorm(1000, 3, 1)
b=rnorm(1000, 6, 1)
hist(a, xlim=c(0,10), col="red")
hist(b, add=T, col=rgb(0, 1, 0, 0.5) )

결과는 다음과 같습니다.alt text

이미 아름다운 답들이 있지만, 저는 이것을 덧붙일 생각을 했습니다.좋아 보이네요. (@Dirk에서 임의의 숫자를 복사했습니다. library(scales)필요함'

set.seed(42)
hist(rnorm(500,4),xlim=c(0,10),col='skyblue',border=F)
hist(rnorm(500,6),add=T,col=scales::alpha('red',.5),border=F)

그 결과는...

enter image description here

업데이트:중복 기능은 일부 사용자에게도 유용할 수 있습니다.

hist0 <- function(...,col='skyblue',border=T) hist(...,col=col,border=border) 

나는 결과를 느낍니다.hist0보다 보기에 더 예뻐요.hist

hist2 <- function(var1, var2,name1='',name2='',
              breaks = min(max(length(var1), length(var2)),20), 
              main0 = "", alpha0 = 0.5,grey=0,border=F,...) {    

library(scales)
  colh <- c(rgb(0, 1, 0, alpha0), rgb(1, 0, 0, alpha0))
  if(grey) colh <- c(alpha(grey(0.1,alpha0)), alpha(grey(0.9,alpha0)))

  max0 = max(var1, var2)
  min0 = min(var1, var2)

  den1_max <- hist(var1, breaks = breaks, plot = F)$density %>% max
  den2_max <- hist(var2, breaks = breaks, plot = F)$density %>% max
  den_max <- max(den2_max, den1_max)*1.2
  var1 %>% hist0(xlim = c(min0 , max0) , breaks = breaks,
                 freq = F, col = colh[1], ylim = c(0, den_max), main = main0,border=border,...)
  var2 %>% hist0(xlim = c(min0 , max0),  breaks = breaks,
                 freq = F, col = colh[2], ylim = c(0, den_max), add = T,border=border,...)
  legend(min0,den_max, legend = c(
    ifelse(nchar(name1)==0,substitute(var1) %>% deparse,name1),
    ifelse(nchar(name2)==0,substitute(var2) %>% deparse,name2),
    "Overlap"), fill = c('white','white', colh[1]), bty = "n", cex=1,ncol=3)

  legend(min0,den_max, legend = c(
    ifelse(nchar(name1)==0,substitute(var1) %>% deparse,name1),
    ifelse(nchar(name2)==0,substitute(var2) %>% deparse,name2),
    "Overlap"), fill = c(colh, colh[2]), bty = "n", cex=1,ncol=3) }

의 결과

par(mar=c(3, 4, 3, 2) + 0.1) 
set.seed(100) 
hist2(rnorm(10000,2),rnorm(10000,3),breaks = 50)

이라

enter image description here

다음은 "클래식" R 그래픽에서 수행할 수 있는 방법의 예입니다.

## generate some random data
carrotLengths <- rnorm(1000,15,5)
cucumberLengths <- rnorm(200,20,7)
## calculate the histograms - don't plot yet
histCarrot <- hist(carrotLengths,plot = FALSE)
histCucumber <- hist(cucumberLengths,plot = FALSE)
## calculate the range of the graph
xlim <- range(histCucumber$breaks,histCarrot$breaks)
ylim <- range(0,histCucumber$density,
              histCarrot$density)
## plot the first graph
plot(histCarrot,xlim = xlim, ylim = ylim,
     col = rgb(1,0,0,0.4),xlab = 'Lengths',
     freq = FALSE, ## relative, not absolute frequency
     main = 'Distribution of carrots and cucumbers')
## plot the second graph on top of this
opar <- par(new = FALSE)
plot(histCucumber,xlim = xlim, ylim = ylim,
     xaxt = 'n', yaxt = 'n', ## don't add axes
     col = rgb(0,0,1,0.4), add = TRUE,
     freq = FALSE) ## relative, not absolute frequency
## add a legend in the corner
legend('topleft',c('Carrots','Cucumbers'),
       fill = rgb(1:0,0,0:1,0.4), bty = 'n',
       border = NA)
par(opar)

이와 관련된 유일한 문제는 히스토그램 중단이 정렬되어 있으면 훨씬 좋아 보인다는 것입니다. 이는 수동으로 수행해야 할 수 있습니다(전달된 인수에서).hist).

여기 제가 기본 R에서만 준 ggplot2와 같은 버전이 있습니다.@nullglob에서 복사했습니다.

데이터를 생성합니다.

carrots <- rnorm(100000,5,2)
cukes <- rnorm(50000,7,2.5)

ggplot2처럼 데이터 프레임에 넣을 필요가 없습니다.이 방법의 단점은 그림의 세부 사항을 훨씬 더 많이 써야 한다는 것입니다.장점은 그림의 더 많은 세부 정보를 제어할 수 있다는 것입니다.

## calculate the density - don't plot yet
densCarrot <- density(carrots)
densCuke <- density(cukes)
## calculate the range of the graph
xlim <- range(densCuke$x,densCarrot$x)
ylim <- range(0,densCuke$y, densCarrot$y)
#pick the colours
carrotCol <- rgb(1,0,0,0.2)
cukeCol <- rgb(0,0,1,0.2)
## plot the carrots and set up most of the plot parameters
plot(densCarrot, xlim = xlim, ylim = ylim, xlab = 'Lengths',
     main = 'Distribution of carrots and cucumbers', 
     panel.first = grid())
#put our density plots in
polygon(densCarrot, density = -1, col = carrotCol)
polygon(densCuke, density = -1, col = cukeCol)
## add a legend in the corner
legend('topleft',c('Carrots','Cucumbers'),
       fill = c(carrotCol, cukeCol), bty = 'n',
       border = NA)

enter image description here

@더크 에델뷔텔:기본 아이디어는 훌륭하지만 표시된 코드는 개선할 수 있습니다.[설명하는 데 시간이 오래 걸리기 때문에 코멘트가 아닌 별도의 답변을 드립니다.]

hist()함수는 기본적으로 그림을 그리므로 추가해야 합니다.plot=FALSE선택.게다가, 플롯 영역을 다음과 같이 설정하는 것이 더 명확합니다.plot(0,0,type="n",...)축 레이블, 플롯 제목 등을 추가할 수 있는 호출입니다.마지막으로 두 히스토그램을 구분하기 위해 음영을 사용할 수도 있다는 점을 언급하고 싶습니다.코드는 다음과 같습니다.

set.seed(42)
p1 <- hist(rnorm(500,4),plot=FALSE)
p2 <- hist(rnorm(500,6),plot=FALSE)
plot(0,0,type="n",xlim=c(0,10),ylim=c(0,100),xlab="x",ylab="freq",main="Two histograms")
plot(p1,col="green",density=10,angle=135,add=TRUE)
plot(p2,col="blue",density=10,angle=45,add=TRUE)

그리고 결과는 다음과 같습니다(RStudio 때문에 약간 너무 넓습니다 :-).

enter image description here

플로틀리의 R API는 당신에게 유용할 것입니다.아래 그래프는 여기 있습니다.

library(plotly)
#add username and key
p <- plotly(username="Username", key="API_KEY")
#generate data
x0 = rnorm(500)
x1 = rnorm(500)+1
#arrange your graph
data0 = list(x=x0,
         name = "Carrots",
         type='histogramx',
         opacity = 0.8)

data1 = list(x=x1,
         name = "Cukes",
         type='histogramx',
         opacity = 0.8)
#specify type as 'overlay'
layout <- list(barmode='overlay',
               plot_bgcolor = 'rgba(249,249,251,.85)')  
#format response, and use 'browseURL' to open graph tab in your browser.
response = p$plotly(data0, data1, kwargs=list(layout=layout))

url = response$url
filename = response$filename

browseURL(response$url)

전체 공개:저는 그 팀에 있습니다.

Graph

멋진 답변들이 너무 많지만 제가 방금 함수를 썼기 때문에 (plotMultipleHistograms()이를 위해 'basicPlotterR' 패키지) 함수에 다른 답변을 추가하려고 했습니다.

이 함수의 장점은 적절한 X 및 Y 축 한계를 자동으로 설정하고 모든 분포에서 사용하는 공통 빈 집합을 정의한다는 것입니다.

사용 방법은 다음과 같습니다.

# Install the plotteR package
install.packages("devtools")
devtools::install_github("JosephCrispell/basicPlotteR")
library(basicPlotteR)

# Set the seed
set.seed(254534)

# Create random samples from a normal distribution
distributions <- list(rnorm(500, mean=5, sd=0.5), 
                      rnorm(500, mean=8, sd=5), 
                      rnorm(500, mean=20, sd=2))

# Plot overlapping histograms
plotMultipleHistograms(distributions, nBins=20, 
                       colours=c(rgb(1,0,0, 0.5), rgb(0,0,1, 0.5), rgb(0,1,0, 0.5)), 
                       las=1, main="Samples from normal distribution", xlab="Value")

enter image description here

plotMultipleHistograms()함수는 임의의 수의 분포를 취할 수 있으며 모든 일반적인 플로팅 매개변수가 함수와 함께 작동해야 합니다(예:las,main등).

언급URL : https://stackoverflow.com/questions/3541713/how-to-plot-two-histograms-together-in-r

반응형