R ggplot Code Sheet
R - ggplot2 Code Sheet
패키지 불러오기: ggplot2 / plyr /[plyr 데이터 함수]
ddply, ldply, dlply ( d->d, l->d, d->l : 추출 -> 반환 )ddply( df, factors, function, 새로운 변환 값들 )
revalue( df, c("기존열" = "새로운 열이름", "기존열" = "새로운 열이름") )
fill: 채우기
color: 테두리
* '점'의 경우 다름
일반적으로: color를 씀
21 ~ 25번: 테두리가 따로 있어서 fill - color 따로 씀
1. 매핑 Mapping
ggplot( data = df
aes(x= X / factor(X) 연속변수를 이산변수로 변환
/ reorder(X, k) X를 k에 따라 재정렬
/ interaction(x1, x2) 변수들을 조합함
y= Y 얘를 설정하지 않으면 y가 빈도수가 됨
fill= OX 이 변수를 기준으로 색을 칠한다
color=
group= 그룹화 (데이터를 잘못 묶는 것을 방지)
order= desc(OX) 순서뒤집기
linetype= 1,2,3 선, 점선, 점
shape=
size=
2. 설정 Setting - 그래프 설정
# 막대 그래프
geom_bar( stat = "identity" / "bin"
fill = "lightblue" / 색깔 채우기
color = "black" / 테두리 색깔
position = position_dodge() / "dodge" 나란히수평 막대
"identity" 음수 막대도 정의할 수 있음, 누적되지 않음
"stack" 누적 막대
size = 0 ~ 1
width = 0 ~ 1 dodge>width면 막대 사이 간격 생김
# 라벨 표기
geom_text( aes( label = Y 실제 표기 데이터
label = Name 산점도 점에 라벨 붙이기
y = y축 위치
vjust = 1.5 양수: 기준 아래
hjust = 0 / 1 왼쪽 정렬, 오른쪽 정렬
color =
position = 위치 설정
size =
# 그래프 길이 설정
geom_segment( aes( yend = Y y값이 Y까지만 가게함
xend = 0
x= , y= )
geom_line(data=predicted 모형 적합선 추가 시
linetype=1,2,3 "solid" "dashed" "dotted"
size= / color= / position=
stat="density", 커널 밀도 곡선 그릴때
adjust=0~1~ 1이 기본값, 커질수록 평활
geom_hline/vline/abline 직선 그림
(yintercept= / xintercept= / intercept= , slope=
data= / aes / linetype / size / color
geom_point(size= / color= / fill="white"/ position= /
shape=1 ~ 100
position=position_jitter() 랜덤으로 점이 움직임
width=, height= 설정할 수도 있음
#음영 그래프
geom_area(color=
size= 0.2 영역 사이의 선
alpha=0.4 투명도
#신뢰구간 추가
geom_ribbon( aes(ymin= / ymax= )
alpha=0.2
#여백 러그 추가 (marginal rug)
geom_rug( position = "jitter", size = 0.2
geom_histogram( binwidth = 10, origin = 5 빈너비10, 경계는 5부터 설정
fill/color
#커널 밀도 곡선
geom_density()
#도수 다각형
geom_freqpoly( binwidth =
geom_boxplot( width =
notch = TRUE
x=1 한 집단만 표시할 때 넣어야 하는 인수
outlier.size / outlier.shape
outlier.color / outlier.fill
geom_violin( trim = TRUE/FALSE F는 꼬리유지
scale = "count" 각 집단의 관측개수에 비례하게 면적으로 조절
adjust = 0 ~ 1 ~
# 윌킨슨 점 그래프 (Wilkinson)
- 클리블랜드 점 그래프는 geom_point() 씀
geom_dotplot( binwidth =
method = "histodot" 빈을 고정해 히스토그램처럼 배열
stackdir = "center" "centerwhole" 정렬 방식
binaxis = "y" y축 상에 점을 찍고 x축으로 그룹화
# 오차 막대
geom_errorbar( aes(ymin= , ymax=
width = 0.2,
position= position_dodge(0.9)
besided 막대에서는 bar와 동일하게 포지션을 설정
# 윌킨슨 점 그래프 (Wilkinson)
- 클리블랜드 점 그래프는 geom_point() 씀
geom_dotplot( binwidth =
method = "histodot" 빈을 고정해 히스토그램처럼 배열
stackdir = "center" "centerwhole" 정렬 방식
binaxis = "y" y축 상에 점을 찍고 x축으로 그룹화
# 오차 막대
geom_errorbar( aes(ymin= , ymax=
width = 0.2,
position= position_dodge(0.9)
besided 막대에서는 bar와 동일하게 포지션을 설정
3. 설정 Setting - 배경, 범례 등
xlab( Xname ) / ylab( Yname )
xlim(0,100)
ylim( 0, max(Y) )
ggtitle(" ") 제목 설정
개행문자: "/n"
[ggplot2의 텍스트 = "테마 요소" + "텍스트 도형"]
[테마요소] [텍스트 도형] [설명, 예시]family family Helvetica, Times, Courier
face fontface plain, bold, italic, bold.italic
color color 색상
size size
hjust hjust
vjust vjust
angle angle 각도
lineheight lineheight 줄 간격을 배수로 변경
# theme: 제목/축라벨/눈금 등 테마 속성들의 외형을 설정함
theme_bw() 설정된 배경1theme_grey() 설정된 배경2
theme_set( theme_?() ) 기본 배경 설정
theme(
기본구조: theme( 옵션 = element_xx
xx: blank, line, rect, text
1) 그래프 영역
panel.grid.major.x / y = element_blank() 큰 격자 지움
panel.grid.minor.x / y = element_line(
color = "", linetype = "") 작은 격자 설정
panel.background = element_rect(fill=
panel.border = element_rect(fill=NA, size=2, color=
2) 텍스트 옵션
axis.title.x / y / 축 라벨 외형
axis.ticks.x / y / 눈금표시 라벨 외형
plot.title = element_text( size= ,color= 제목 텍스트 외형 조절
lineheight= ~ 1 ~
face = "bold.italic"
family = " "
3) 면 분할 옵션
strip.text.x / y / 분할 면 라벨 외형
strip.background = element_rect( fill = "pink" )
4) 범례 옵션
legend.title( face = "italic", family="Times", color, size 범례 제목 외형
legend.text( element_text(face, family, color, size 범례 항목 외형
legend.background = element_rect(
element_blank( 전체적인 테두리 제거
legend.key = element_blank( 범례의 각 항목 테두리 제거
legend.position = c(x,y) 범례 위치 변경
"none" "top" "bottome"
legend.justification = c(x,y) 위치 선정 기준
(0.5, 0.5)가 기본 - 범례의 중앙
# 기타
labs(fill = "제목" 범례 제목 설정
color="제목1", size = "제목2\n(이거) "
> 구분 기준에 따른 범례 설정
> color로 구분한 범례의 제목은 제목1
size로 구분한 범례의 제목은 제목2
(이거)
guides( fill = guide_legend( reverse = TRUE 순서 뒤집기
title = NULL 제목 제거
title = NULL 제목 제거
# 내 테마 설정
mytheme = theme_bw() +theme(text = element_text(color="darkred"),
axis.title = element_text(size=rel(1.3)))
4. 설정 Setting - 모양, 색상 설정
# discrete = hue
brewer: ColorBrewer 팔레트 모든 팔레트 보여주기 커맨드: display.brewer.all()
manual: 사용자 지정 색상
gradient: 그라데이션 - 연속 변수에 색상 적용
discrete: 색상환에서 등간격으로 분포하는 색깔들 (hue와 동일)
grey: 회색조 팔레트
scale_fill_brewer(palette = "Set1" "Pastel1" "Pastel2" "Blues"
scale_fill_manual(values = c("#669933", "#FFCC66")
c("black", "blue")
guide = FALSE 범례 지움
scale_fill_gradient(
scale_fill_gradient( 2가지 색깔 그라데이션
low= / high=
scale_fill_gradient2( 가운데서부터 분화하는 그라데이션
low= / mid= / high=
scale_fill_gradientn( n개의 색깔로 된 그라데이션 (색들은 등간격)
colors = c("",...
low = "black", high = "white" 그래디언트 표현
breaks(seq(20, 120, by=20 단계 구간 설정
guide=guide_legend() 내부 범례 설정
limits= c(0,3000) 한계 설정
scale_fill_discrete( fill/범례에 대한 구체적 설정
l = 1 ~ 100
lightness = 기본: 65, 낮을수록 어두워짐
name=" " 범례 제목 설정
limits = c("", ""... 항목의 순서를 변경 (범례)
labels = c("", "") 범례 실제 표기 변경
guide = FALSE 범례 제거
guide = guide_legend(reverse=TRUE)
scale_fill_grey(
-----
scale_color_brewer( palette =
scale_color_manual(
scale_color_gradient(
scale_color_discrete(
scale_color_grey(
-----
scale_size_area( 점의 면적을 수치형 값에 비례하도록
max_size = 점의 최대 크기
scale_shape_manual(values = c(1,4)
scale_linetype(
5. stat 설정
stat_function( fun = , geom = )
stat_bin2d( bins = 30) 기본설정: 30, 30*30 개의 빈으로 나눔 (비닝화)
stat_smooth( method = lm 선형회귀직선
loess 국지가중치 다중회귀
glm 로지스틱 회귀
se = FALSE 신뢰구간 끄기
color/linetype/size
family =
fullrange= TRUE 그래프 끝까지 예측구간 표시
stat_summary( fun.x / fun.y = "mean" 적용할 함수
geom="point" 적용할 그래픽스
shape/size/fill/color
# 2D 커널 밀도 추정치
stat_density2d( color = ..level.. 등고선의 색상 = 곡선의 '높이'
fill = ..density.. 색상 = 밀도추정치
alpha = ..density.. 투명도 = 밀도추정치
geom= "raster" "tile" 렌더링 방식
contour = FALSE
10. 기타 추가 설정
annotate("text", x= , y= , label = "Canada" 주석을 직접 추가
축이 연속적인 경우에는 x, y에 Inf, -Inf를 넣을 수 있음
size = / color =
fontface = "italic"
family = "serif"
vjust= / hjust=
parse = TRUE 수식을 담은 문자열 추가 가능
("segment", 선분/화살표 추가
x= , xend= , y= , yend= ,
color / size
arrow=arrow() 기본설정은 화살표
arrow=arrow(ends="both" "left" "right",
angle=90,
length=unit(0.2, "cm") )
("rect", 음영 추가
xmin, xmax, ymin, ymax
alpha, fill
facet_grid( 그래프를 분할 (측면보기)
분할기준 변수 ~ . 수직 분할
. ~ 변수 수평 분할
변수1 ~ 변수2 수직/수평 동시 분할
scales = "free_x", "free_y", "free" x/y/두 축 눈금 자유롭게
facet_wrap( ~ 비슷한데 얘는 .을 안씀
nrow= / ncol= 기본설정이 정사각형 배열이라서
필요에 따라 재설정 필요
# 분할 면 라벨과 헤더 외형 변경
theme( strip.text = element_text( face = "bold", size = rel(1.5))
strip.background = element_rect( fill = "lightblue",
color = "black",
size = 1
approx(x,y,n= ) 내삽법 - x와 y로 된 리스트 반환
댓글
댓글 쓰기