IT

ggplot2에서 산점도 행렬(쌍() 등가) 생성

itgroup 2023. 6. 12. 21:17
반응형

ggplot2에서 산점도 행렬(쌍() 등가) 생성

다음을 사용하여 산점도 행렬을 표시할 수 있습니까?ggplot2,사용.ggplot색상, 모양 등에 추가 요인을 매핑하고 매끄럽게 추가하는 등의 좋은 기능이 있습니까?

저는 비슷한 것에 대해 생각하고 있습니다.base기능.pairs.

저는 계속 이것을 하고 싶지만, 줄거리 매트릭스는 쓰레기입니다.Hadley는 대신 GGally 패키지를 사용할 것을 권장합니다.데이터 프레임에 비연속 변수를 사용할 수 있도록 크게 개선된 쌍 그림인 gg 쌍 함수가 있습니다.변수 유형에 따라 각 정사각형에 서로 다른 그림이 표시됩니다.

library(GGally)
ggpairs(iris, aes(colour = Species, alpha = 0.4))

여기에 이미지 설명 입력

그림 행렬을 사용해 볼 수도 있습니다.

  library(ggplot2)
  data(mtcars)
  plotmatrix(mtcars[,1:3])

to mmpg(mtcars 단위의 첫 번째 열)는 요인이 되어서는 안 됩니다.확인해보지는 않았지만, 굳이 확인해야 할 이유는 없습니다.하지만 저는 산점도를 얻습니다 :)


참고: 향후 참조를 위해,plotmatrix()기능이 다음으로 대체되었습니다.ggpairs()의 기능GGally이 질문에 대한 아래의 다른 응답에서 @naught101이 시사하는 바와 같이 패키지.

만약 누군가가 있습니다.ggplot목적어(아니오)ggmatrix의 경우와 마찬가지로ggpairs()), 솔루션은 데이터를 두 번 녹이는 것입니다.ggplot익살스럽게 facet_wrap보다 나을 것입니다facet_grid표시된 영역을 제한할 때, 주어진 경우scales = 'free'매개 변수가 제공됩니다.

require(ggplot2) 
require(dplyr)
require(tidyr)

gatherpairs <- function(data, ..., 
                        xkey = '.xkey', xvalue = '.xvalue',
                        ykey = '.ykey', yvalue = '.yvalue',
                        na.rm = FALSE, convert = FALSE, factor_key = FALSE) {
  vars <- quos(...)
  xkey <- enquo(xkey)
  xvalue <- enquo(xvalue)
  ykey <- enquo(ykey)
  yvalue <- enquo(yvalue)

  data %>% {
    cbind(gather(., key = !!xkey, value = !!xvalue, !!!vars,
                 na.rm = na.rm, convert = convert, factor_key = factor_key),
          select(., !!!vars)) 
  } %>% gather(., key = !!ykey, value = !!yvalue, !!!vars,
               na.rm = na.rm, convert = convert, factor_key = factor_key)
}

iris %>% 
  gatherpairs(Sepal.Length, Sepal.Width, Petal.Length, Petal.Width) %>% {
  ggplot(., aes(x = .xvalue, y = .yvalue, color = Species)) +
      geom_point() + 
      geom_smooth(method = 'lm') +
      facet_wrap(.xkey ~ .ykey, ncol = length(unique(.$.ykey)), scales = 'free', labeller = label_both) +
      scale_color_brewer(type = 'qual')
}

여기에 이미지 설명 입력

산점도 행렬을 시도합니다.매우 유연하고 보기 좋은 대화형 차트를 생성합니다.

library(scatterPlotMatrix)
scatterPlotMatrix(iris, zAxisDim = "Species")

여기에 이미지 설명 입력

언급URL : https://stackoverflow.com/questions/3735286/create-a-matrix-of-scatterplots-pairs-equivalent-in-ggplot2

반응형