이 ggplot2 플롯을 복제 할 수 없습니다.

Sep 06 2020

ggrough라이브러리 에서 예제를 복제 할 수 없습니다 (https://xvrdm.github.io/ggrough/articles/Customize%20chart.html). 특히 다음 플롯을 복제하려고합니다 (글꼴 측면 제외).

코드는 위의 "Kindergarten"헤더 아래에있는 동일한 링크에서 가져온 것입니다.

다음 코드를 사용하고 있습니다.

library(hrbrthemes)
library(tidyverse)
library(gcookbook)
library(ggplot2)
library(ggrough)
ggplot(uspopage, aes(x=Year, y=Thousands, fill=AgeGroup)) + 
    geom_area(alpha=0.8) +
    scale_fill_ipsum() +
    scale_x_continuous(expand=c(0,0)) +
    scale_y_comma() -> p 

options <- list(GeomArea=list(fill_style="hachure", 
                              angle_noise=0.5,
                              gap_noise=0.2,
                              gap=1.5,
                              fill_weight=1))
get_rough_chart(p, options)

그러나 위의 내용을 복제 할 수 없습니다. 내가 얻는 것은 다음과 같습니다.

다시 말하지만 글꼴에 대해서는 걱정하지 않지만 음영 처리 된 geom_area가 작동하도록하고 싶습니다. 현재는 전혀 렌더링되지 않습니다. 참고로 다음은 p객체가 산출하는 것입니다 (즉, ggrough처리 를 거치기 전의 플롯 ).

또한를 사용하는 "Blueprint"예제를 복제 할 수 geom_col있습니다. 따라서를 ggrough처리하는 데 문제가있는 것처럼 geom_area보이지만 확실하지 않습니다.

답변

8 Z.Lin Sep 10 2020 at 15:04

ggrough 패키지는 geom_area"polyline"이라는 이름을 가진 xml 노드에서 대상 영역을 찾기 때문에 현재 버전의 ggplot2에서 제대로 작동하지 않습니다 . 이전 버전의 ggplot2에서는 각 영역이 폴리 라인으로 둘러싸여 있기 때문에 아마도 잘 작동했을 것입니다. 그러나 최신 버전에서는 더 이상 그렇지 않습니다 ( 3.3.0의 주요 변경 사항 참조 ).

다음이 효과가 있는지 확인하십시오.

  1. parse_*"polyline"이 아닌 "polygon"을 찾는 함수 버전을 정의하십시오 .
parse_polygons <- function (svg) {
  shape <- "polygon" # was "polyline" in ggrough:::parse_areas
  keys <- NULL
  ggrough:::parse_shape(svg, shape, keys) %>% {
    purrr::map(., 
               ~purrr::list_modify(.x, 
                                   points = stringr::str_squish(.x$points) %>% 
                                     {stringr::str_glue("M{.}Z")}, 
                                   shape = "path"))
  }
}
  1. parse_polygonsGeomArea 레이어에 대해 새로 정의 된 것을 사용하려면 ggrough에서 해당 내보내기되지 않은 함수를 변경하십시오 .

또한, 나는 (원본에서 누락 된 것으로 나타났다하지만 정말 GeomArea의보다 일반적인 경우이다)부터 GeomViolin 이동 GeomRibbon에 추가 한 parse_areasparse_polygons이 같은 문제에 직면 해 있기 때문에.

(참고 : GeomSmooth도 중단 될 수 있지만 GeomRibbon / GeomViolin에 비해 파싱 기능이 약간 더 조정될 것이라고 생각하며 사용 사례가 보이지 않습니다 ...)

trace(ggrough:::parse_rough, edit = TRUE)

# paste the following function into the pop-up window
function (svg, geom) {
  rough_els <- list()
  if (geom %in% c("GeomCol", "GeomBar", "GeomTile", "Background")) {
    rough_els <- append(rough_els, parse_rects(svg))
  }
  if (geom %in% c("GeomSmooth", "Background")) {   # removed GeomArea / GeomViolin from here
    rough_els <- append(rough_els, parse_areas(svg))
  }
  if (geom %in% c("GeomArea", "GeomRibbon", "GeomViolin")) {  # new condition here
    rough_els <- append(rough_els, parse_polygons(svg))
  }
  if (geom %in% c("GeomPoint", "GeomJitter", "GeomDotPlot", "Background")) {
    rough_els <- append(rough_els, parse_circles(svg))
  }
  if (geom %in% c("GeomLine", "GeomSmooth", "Background")) {
    rough_els <- append(rough_els, parse_lines(svg))
  }
  if (geom %in% c("Background")) {
    rough_els <- append(rough_els, parse_texts(svg))
  }
  purrr::map(rough_els, ~purrr::list_modify(.x, geom = geom))
}

테스트:

library(ggplot2)
library(ggrough)

uspopage <- gcookbook::uspopage
p <- ggplot(uspopage, aes(x=Year, y=Thousands, fill=AgeGroup)) + 
  geom_area(alpha=0.8) +
  scale_x_continuous(expand=c(0,0)); p
options <- list(GeomArea=list(fill_style="hachure", 
                              angle_noise=0.5,
                              gap_noise=0.2,
                              gap=1.5,
                              fill_weight=1))
get_rough_chart(p, options)

다음에 대한 추가 테스트 geom_ribbon:

# using example from geom_ribbon help page
pp <- data.frame(year = 1875:1972, level = as.vector(LakeHuron)) %>%
  ggplot(aes(year)) +
  geom_ribbon(aes(ymin = level - 1, ymax = level + 1), 
              fill = "grey70")
options <- list(GeomRibbon=list(fill_style="hachure", 
                                angle_noise=0.5,
                                gap_noise=0.2,
                                gap=1.5,
                                fill_weight=1))
get_rough_chart(pp, options)

세션 정보 :

R version 4.0.1 (2020-06-06)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 15063)

Matrix products: default

locale:
[1] LC_COLLATE=English_Singapore.1252  LC_CTYPE=English_Singapore.1252   
[3] LC_MONETARY=English_Singapore.1252 LC_NUMERIC=C                      
[5] LC_TIME=English_Singapore.1252    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] gdtools_0.2.2 dplyr_1.0.0   ggrough_0.1.0 ggplot2_3.3.2

loaded via a namespace (and not attached):
 [1] Rcpp_1.0.5        cpp11_0.2.1       pillar_1.4.6      compiler_4.0.1   
 [5] plyr_1.8.6        Rmisc_1.5         forcats_0.5.0     tools_4.0.1      
 [9] boot_1.3-25       digest_0.6.25     jsonlite_1.7.1    lifecycle_0.2.0  
[13] tibble_3.0.3      gtable_0.3.0      lattice_0.20-41   pkgconfig_2.0.3  
[17] rlang_0.4.7       rstudioapi_0.11   yaml_2.2.1        xml2_1.3.2       
[21] withr_2.2.0       stringr_1.4.0     htmlwidgets_1.5.1 systemfonts_0.3.1
[25] generics_0.0.2    vctrs_0.3.4       grid_4.0.1        tidyselect_1.1.0 
[29] data.table_1.12.8 svglite_1.2.3.2   glue_1.4.2        R6_2.4.1         
[33] gcookbook_2.0     tidyr_1.1.0       reshape2_1.4.4    purrr_0.3.4      
[37] farver_2.0.3      magrittr_1.5      htmltools_0.5.0   scales_1.1.1     
[41] ellipsis_0.3.1    fortunes_1.5-4    colorspace_1.4-1  labeling_0.3     
[45] stringi_1.5.3     munsell_0.5.0     crayon_1.3.4     
5 SteffenMoritz Sep 08 2020 at 10:05

댓글이 너무 길기 때문에 답으로 쓰고 있습니다.

나는 또한 ggrough 당신을 위해 패키지를 시도했습니다 .

github readme의 다음 예제는 완벽하게 작동합니다.

library(ggplot2)
count(mtcars, carb) %>%
  ggplot(aes(carb, n)) +
  geom_col() + 
  labs(title="Number of cars by carburator count") + 
  theme_grey(base_size = 16) -> p 
p

library(ggrough)
options <- list(
  Background=list(roughness=8),
  GeomCol=list(fill_style="zigzag", angle_noise=0.5, fill_weight=2))
get_rough_chart(p, options)

그러나 내가 당신의 예를 시도 할 때 :

library(hrbrthemes)
library(tidyverse)
library(gcookbook)
library(ggplot2)
library(ggrough)
ggplot(uspopage, aes(x=Year, y=Thousands, fill=AgeGroup)) + 
    geom_area(alpha=0.8) +
    scale_fill_ipsum() +
    scale_x_continuous(expand=c(0,0)) +
    scale_y_comma() -> p 
p

여기까지는 괜찮습니다. 그러면 다음 이미지가 표시됩니다.

이제 ggrough 부분을 추가해야합니다.

options <- list(GeomArea=list(fill_style="hachure", 
                              angle_noise=0.5,
                              gap_noise=0.2,
                              gap=1.5,
                              fill_weight=1))
get_rough_chart(p, options)

나는 당신과 거의 같은 결과를 얻습니다.

나는 당신과 같은 결론에 도달했습니다.

따라서 geom_area를 처리하는 데 문제가있는 것 같습니다.

GeomCol위의 자동차 수의 예 에 대해 ggrough 부분에 대해 모든 동일한 설정을 성공적으로 사용할 수도 있습니다 (유일한 차이점은 ).

Github 페이지에 따르면 :

ggrough는 진행중인 작업이며 여전히 큰 버그가 있습니다. 기부를 환영합니다! "

그들은 2 년 전에 마지막 Git 커밋을했습니다.

이제 만들려는 플롯이 자신의 예제에서 나온 것이기 때문에 한 번 작동했다고 확신합니다. (내 말은 그들이 가짜 음모를 업로드하는 이유를 의미합니다)

그래서 당신이 정말로 절망적이라면 시도해 볼 수 있습니다.

  • 2 년 전의 ggplot2 버전 (및 기타 필수 패키지) 설치

  • ggrough패키지 에서 이전 커밋 버전을 설치 합니다. 아마도 그들은 한때 작동했던 예제를 깨뜨린 커밋을 만들었을 것입니다.

또는 패키지를 수정하려고합니다.)