- R을 이용한 과학 저널 그래프 그리기2023년 12월 17일 20시 35분 02초에 업로드 된 글입니다.작성자: r-code-for-data-analysis
최근에 논문에 들어갈 그래프 형태를 검색하다가 좋은 패키지를 찾았다.
한국의 민승현 교수님이 공부하면서 필요에 의해 만든 R 패키지라 더 친근감이 들었다. (감사합니다. ^^)
smplot 이 한번 더 발전하여 smplot2가 되었다.
https://github.com/smin95/smplot2
GitHub - smin95/smplot2
Contribute to smin95/smplot2 development by creating an account on GitHub.
github.com
그럼 본격적으로 기존의 ggplot과 비교해보자.
devtools::install_github('smin95/smplot2', force = TRUE) library(tidyverse) # it has ggplot2 package library(cowplot) # it allows you to save figures in .png file library(smplot2) library(patchwork) p1 <- ggplot(data = mpg, mapping = aes(x = displ, y = hwy, color = class)) + geom_point() p2 <- ggplot(data = mpg, mapping = aes(x = displ, y = hwy, color = class)) + geom_point() + sm_corr_theme() p1+p2
왼쪽이 일반적인 ggplot이고, 오른쪽이 smplot2 패키지로 마사지를 한 것이다. 사용법도 쉽다. sm_corr_theme()만 붙이면 됨. 범례를 삭제하고 싶으면
sm_corr_theme(legends = FALSE)
외곽 테두리를 제거하고 싶으면
sm_corr_theme(borders = FALSE)
추세선을 넣고 싶으면 sm_statCorr()를 쓴다.
기본은 Pearson의 상관관계 테스트로 R, p 값이 써지는데, Spearman 상관관계 테스트가 필요하면 아래와 같이 쓴다.
corr_method = 'spearman',
p3 <- ggplot(data = mtcars, mapping = aes(x = drat, y = mpg)) + geom_point(shape = 21, fill = '#0f993d', color = 'white', size = 3) + sm_statCorr() p4 <- ggplot(data = mtcars, mapping = aes(x = drat, y = mpg)) + geom_point(shape = 21, fill = '#0f993d', color = 'white', size = 3) + sm_statCorr(color = '#0f993d', corr_method = 'spearman', linetype = 'dashed') p3+p4
다음은 scatter plot 만큼 많이 사용하는 boxplot이다.
첫 번째 것은 일반적인 ggplot으로 그린 것이고, 두 번째는 sm_boxplot을 쓰고 속성을 point.params로 준 것이다.
세 번째 것은 점의 색을 칠한 것이고, 3개 색깔이라 sm_palette(3)을 사용하였다.
p1 <- ggplot(data = df, mapping = aes(x = Day, y = Value, color = Day)) + geom_boxplot() + geom_jitter(width = 0.15) p2 <- ggplot(data = df, mapping = aes(x = Day, y = Value, color = Day)) + geom_boxplot() + geom_jitter(width = 0.15) + ggtitle('Visual improvement after treatment')+ sm_minimal(legends = FALSE) p3 <- ggplot(data = df, mapping = aes(x = Day, y = Value, fill = Day)) + sm_boxplot(point.params = list(shape = 21, color = 'white', size = 2.5, alpha = 0.65)) + ggtitle('Visual improvement after treatment') + scale_fill_manual(values = sm_palette(3)) p1+p2+p3 save_plot('boxplot.jpg', my_boxplot, base_asp = 1)
Raincloud 플롯 : 개별 데이터+ 바이올린 플롯+ 상자 플롯 --> 원시 데이터, 확률 밀도 및 중앙값, 분위수 표시
매우 간단하게 sm_raincloud()로 그릴 수 있다. 가로로 눕히려면 vertical=F를 넣으면 됨.
p1 <- df %>% ggplot(aes(x = Day, y = Value, fill = Day)) + sm_raincloud() + scale_fill_manual(values = sm_color('blue','orange', 'pink')) p2 <- df %>% ggplot(aes(x = Day, y = Value, fill = Day)) + sm_raincloud(vertical = FALSE) + scale_fill_manual(values = sm_color('blue','orange', 'pink')) p1+p2
좀 더 복잡한 그래프를 그려보자. 아래와 같이 SF에 따른 absBP 그래프를 그리는데 Group이 두 종류가 있다.
이를 위에서 보았던 Raincloud로 그리되, 하나의 그래프에 모두 표시하자.
p1 <- ggplot(mapping = aes(x = SF, y = absBP, fill = Group)) + sm_raincloud(data = df2amb, position = position_nudge(x = +0.15)) + sm_raincloud(data = df2norm, which_side = 'left', position = position_nudge(x = -0.15)) + scale_fill_manual(values = sm_color('darkred', 'viridian')) p2 <- ggplot(mapping = aes(x = SF, y = absBP, fill = Group)) + sm_raincloud(data = df2amb, position = position_nudge(x = +0.15), show.legend = FALSE, point.params = list(size = 2, shape = 21, color = 'transparent', show.legend = TRUE, alpha = 0.3, position = sdamr::position_jitternudge(nudge.x = 0.06, seed = 10, jitter.width = 0.06))) + scale_fill_manual(values = sm_color('darkred', 'viridian')) + sm_raincloud(data = df2norm, which_side = 'left', show.legend = FALSE, position = position_nudge(x = -0.15), point.params = list(size = 2, shape = 21, show.legend = TRUE, color = 'transparent', alpha = 0.3, position = sdamr::position_jitternudge(nudge.x = -0.06, seed = 10, jitter.width = 0.06))) + theme(legend.position = c(0.24,0.85), legend.title = element_blank(), legend.text = element_text(size = 11)) + ggtitle('Raincloud plot of two groups') + scale_y_continuous(limits = c(0,2.5)) p1+p2
다음은 sm_slope 그래프이다.
변화에 따른 개별값이 어떻게 변화했는지 보는데 유용하다.
기본 코드와 확장 코드는 아래와 같다. 평균을 중심으로 오차 막대를 그리는데, 기본은 sd(표준편차)이고, 다른 것은 ci (95% confidence interval)와se (standard error)가 있다.
오차 종류의 수식 p1 <- ggplot(data = df, aes(x = beforeAfter, y = Value, fill = beforeAfter)) + sm_slope(group = Subject, labels = c('Before', 'After')) + scale_fill_manual(values= sm_color('blue','orange')) p2 <- ggplot(data = df, aes(x = beforeAfter, y = Value)) + sm_slope(group = Subject, show_mean = TRUE, show_err = TRUE, labels = c('Before', 'After'), point.params = list(fill = sm_color('blue'), color = 'white', size = 2.2, stroke = 0.65, shape = 21, alpha = 0.3), line.params = list(color = sm_color('skyblue'), alpha = 0.3), avgPoint.params = list(color='transparent', shape = 21, size = 4, fill = sm_color('blue')), avgLine.params = list(size = 1, color = sm_color('blue')), err.params = list(size = 1, color = sm_color('blue')), errorbar_type = 'ci') p1+p2
[사용법 관련 자료]
https://smin95.github.io/dataviz/basics-of-ggplot2-and-correlation-plot.html
Chapter 3 Basics of ggplot2 and Correlation Plot | Data Analysis and Visualization in R Using smplot2
Although the default theme of ggplot2 graphs is clean, there are some things that I do not like: Let’s make this graph prettier by using functions from smplot2. - In this example, let’s use sm_corr_theme(). I’ve made this function as a theme suitable
smin95.github.io
참고로 민교수님은 패키지 관련 논문까지 썼으니 대단하다.
https://www.frontiersin.org/articles/10.3389/fgene.2021.802894/full
smplot: An R Package for Easy and Elegant Data Visualization
R, a programming language, is an attractive tool for data visualization because it is free and open source. However, learning R can be intimidating and cumbersome for many. In this report, we introduce an R package called “smplot” for easy and elegant
www.frontiersin.org
728x90반응형'데이터 시각화' 카테고리의 다른 글
R을 이용한 논문용 그래프 (흑백용 패턴 색칠) (1) 2024.01.21 R을 이용한 논문 그래프 그리기2 (1) 2023.12.17 R을 이용한 2020년 국회의원 선거 시각화 (0) 2023.11.12 R을 이용한 통계청 API로 남은 기대 수명 알아보기 (1) 2023.11.11 R을 이용한 한국은행 API로 미국과 한국 이자율 시각화 (0) 2023.11.11 댓글