또한 각 축에 변수를 매핑하는 것 외에도 다음과 같이 여러 시각적인 속성에 변수를 매핑할 수 있음.
col : 시각화에 사용되는 색 지정
label : 시각화를 통해 표현되는 label 지정
size : 시각화에 사용되는 크기 지정
여러 속성을 갖는 glyph
g +geom_point(aes(color = net_users), size =3)
Figure 2: Scatterplot in which net_users is mapped to color.
각 점의 색상을 범주형 net_users 변수에 대응시켜 (aesthetic 추가) Figure 1 를 확장
Glyph 바꾸기
g +geom_text(aes(label = country, color = net_users), size =3)
Figure 3: Scatterplot using both location and label as aesthetics.
점 -> 텍스트
더 많은 aesthetics
g +geom_point(aes(color = net_users, size = roadways))
Figure 4: Scatterplot in which net_users is mapped to color and educ mapped to size.
educ -> 가로축상 위치
gdp -> 세로축상 위치
net_users -> 색상
roadways -> 점 크기
Glyph-ready data
점 하나는 country를 나타냄 (왜 그런가?).
ggplot(data = CIACountries)
모든 데이터프레임이 이렇지는 않음. 6장 참조.
척도
Figure 4 에서 GDP값이 오른쪽으로 꼬리가 긴(right-skewed) 분포를 가지기 때문에 값이 작은 부분에서는 차이를 느끼기 어려움.
g +geom_point(aes(color = net_users, size = roadways)) +coord_trans(y ="log10")
Figure 5: Scatterplot using a logarithmic transformation of GDP that helps to mitigate visual clustering caused by the right-skewed distribution of GDP among countries.
선형 척도 -> (상용)로그 척도 (coord_trans())
모든 척도가 위치에 관한 것은 아님: net_users -> 색상(qualitative); roadways -> 점 크기
가이드
맥락을 제공하여 시각적 단서에 의미 부여
위치 정보: 축, 눈금, 레이블
범례: net_users -> 색상 등 대응 설명
Facets
여러 개의 나란히 놓인 도표
한 도표에 너무 많은 aesthetics(모양, 색상, 크기 등)을 한꺼번에 표시하는 것은 너무 많은 정보를 주어 혼란을 줄 수 있음.
Facet은 여러 그래프를 범주에 따라 병렬적으로 그려 주어 보다 효과적으로 다양한 정보를 제공할 수 있음.
Scatterplot using facets for different ranges of Internet connectivity.
범주형 변수 하나로 구분
facet_grid()
범주형 변수 두 개의 조합으로 구분
층
두 개 이상의 자료표의 데이터를 그래프로 표현해야 할 필요가 종종 있음
메디케어 자료
MedicareCharges 및 MedicareProviders 자료표는 미국 각 주의 의료 절차의 평균 비용에 대한 정보를 담고 있음.
MedicareCharges 표에서 각 행은 각 주에서 관련 평균 비용과 함께 서로 다른 의료 절차(drg)를 나타냄.
ChargesNJ <- MedicareCharges %>%filter(stateProvider =="NJ") # New Jersey only
p <-ggplot(data = ChargesNJ,aes(x =reorder(drg, mean_charge), y = mean_charge) ) +geom_col(fill ="gray") +ylab("Statewide Average Charges ($)") +xlab("Medical Procedure (DRG)") +theme(axis.text.x =element_text(angle =90, hjust =1, size =rel(0.5)))p
Figure 6: Bar graph of average charges for medical procedures in New Jersey.
Aesthetic: drg (mean_charge에 따라 오름차순으로 정렬) -> x, mean_charge -> y
Glyph: 막대 (geom_col())
다른 주와의 비교
p +geom_point(data = MedicareCharges, size =1, alpha =0.3)
Figure 7: Bar graph adding a second layer to provide a comparison of New Jersey to other states. Each dot represents one state, while the bars represent New Jersey.
Glyphs: 막대 — 뉴저지, 점 — 미국 전역의 주
뉴저지의 진료비가 전 의료 절차에 걸쳐 대해 전국에서 가장 높은 수준이라는 것을 쉽게 알 수 있음
R의 표준 데이터 그래픽
1변수 도표
통계학에서 표준적인 데이터 그래픽(Tukey, 1990)은 화려하지는 않으나 단순하고 효과적
종종 하나의 변수에 대한 분포를 이해하는 과정이 필요함
히스토그램
SAT_2010 자료에서 수학 점수(math)를 x에 대응 (수치형).
g <-ggplot(data = SAT_2010, aes(x = math))
geom_histogram()
g +geom_histogram(binwidth =10) +labs(x ="Average Math SAT score")
Figure 8: Histogram showing the distribution of math SAT scores by state.
binwidth 인수로 bin의 넓이를 조절해가면서 자신의 데이터에 가장 적절한 값을 결정해야 함
가로축: SAT 수학 점수 (수치형)
선형 척도
시각적 단서: 위치 및 방향
좌표계: 데카르트 좌표계
밀도 도표
geom_density()로 같은 자료를 핵평활화(kernel smoothing)
g +geom_density(adjust =0.3)
Figure 9: Density plot showing the distribution of average math SAT scores by state.
adjust: geom_histogram()의 binwidth와 비슷한 역할 (핵 대역폭 조절)
막대그래프
SAT_2010 자료의 주별(state) 수학 점수 평균 분포 (범주형)
geom_col()
bc <-ggplot(data =head(SAT_2010, 10), # only the first 10 states (in alphabetical order)aes(x =reorder(state, math), y = math)) +geom_col() +# sort the state names in order of their average math SAT scorelabs(x ="State", y ="Average Math SAT score")
Figure 10: A bar plot showing the distribution of average math SAT scores for a selection of states.
Figure 11: A stacked bar plot showing the distribution of substance of abuse for participants in the HELP study.
다변량 도표
두 개 이상의 변수 사이의 관계를 전달
산점도
두 수치형 변수의 관계
좌표계: 데카르트, x = (변수 1), y = (변수 2)
g <-ggplot(data = SAT_2010, aes(x = expenditure, y = math) # expenditure per pupil (1k USD) ) +geom_point()g
Figure 12: A scatter plot showing the relationship between the average SAT math score and the expenditure per pupil.
산점도 위에 선형 회귀선을 그려 두 변수 사이의 관계를 더 잘 설명할 수 있다.
g <- g +geom_smooth(method ="lm", se =FALSE) +xlab("Average expenditure per student ($1000)") +ylab("Average score on math SAT")g
Figure 13: A scatter plot with the simple linear regression line showing the relationship between the average SAT math score and the expenditure per pupil.
층 추가: SAT_rate (low, medium, high score)
Aesthetic 추가: SAT_rate -> color
SAT_2010 <- SAT_2010 %>%mutate(SAT_rate =cut( sat_pct, breaks =c(0, 30, 60, 100), labels =c("low", "medium", "high") ) )g <- g %+% SAT_2010 # update the data frame that is bound to our plotg +aes(color = SAT_rate)
Figure 14: Scatterplot using the color aesthetic to separate the relationship between two numeric variables by a third categorical variable.
Faceting: facet_wrap()
g +facet_wrap(~ SAT_rate)
Figure 15: Scatterplot using a facet_wrap() to separate the relationship between two numeric variables by a third categorical variable.
NHANES 자료
미국 국민 건강 및 영양조사를 통해 얻은 자료로 개인의 체형이나 성별, 나이 등의 정보를 포함
Height vs Age, by Gender
ggplot(data =slice_sample(NHANES::NHANES, n =1000), aes(x = Age, y = Height, color =fct_relevel(Gender, "male")) # reset factor levels) +geom_point() +geom_smooth() +xlab("Age (years)") +ylab("Height (cm)") +labs(color ="Gender")
Figure 16: A scatterplot for 1,000 random individuals from the NHANES study. Note how mapping gender to color illuminates the differences in height between men and women.
context <-tribble(~year, ~num_people, ~label,1935, 40, "Number of Josephs\nborn each year",1915, 13, "Number of Josephs\nborn each year\nestimated to be alive\non 1/1/2014", 2003, 40, "The median\nliving Joseph\nis 37 years old", )joe <- name_plot +ggtitle("Age Distribution of American Boys Named Joseph") +geom_text(data = context, aes(y = num_people, label = label, color = label) ) +geom_curve(x =1990, xend =1974, y =40, yend =24, arrow =arrow(length =unit(0.3, "cm")), curvature =0.5 ) +scale_color_manual(guide ="none", values =c("black", "#b2d7e9", "darkgray") ) +ylim(0, 42)
Figure 21: Recreation of the age distribution of “Joseph” plot.
name_plot의 data 인수를 수정하여 다른 이름에 대한 유사한 그래프를 얻음
name_plot %+%filter( BabynamesDist, name =="Josephine"& sex =="F")
Figure 22: Age distribution of American girls named “Josephine.”
같은 이름, 다른 성별
facet_wrap()
names_plot <- name_plot +facet_wrap(~sex)names_plot %+%filter(BabynamesDist, name =="Jessie")
Figure 23: Comparison of the name “Jessie” across two genders.
각 이름에 대해 현재 생존한 것으로 예상되는 사람의 수를 세고, 여성을 필터링하고, 생존할 것으로 예상되는 수를 기준으로 정렬한 다음 상위 25명의 결과를 가져옴.
각 이름을 가진 사람들의 연령 중앙값과 1사분위수 및 3사분위수를 계산.
y를 median_age, x를 y를 기준으로 내림차순 정렬한 name으로 지정
w_plot <-ggplot(data = com_fem, aes(x =reorder(name, -median_age), y = median_age)) +xlab(NULL) +ylab("Age (in years)") +ggtitle("Median ages for females with the 25 most common names")