Script )
View(anscombe)
# 평균 구하기 <anscombe 각 열의 평균> # 두 번째 인수가 2이면 열, 1이면 행
apply(anscombe,2,mean)
# 분산 구하기 <anscombe 각 열의 분산>
apply(anscombe,2,var)
# 상관관계
cor(anscombe$x1,anscombe$y1)
cor(anscombe$x2,anscombe$y2)
cor(anscombe$x3,anscombe$y3)
cor(anscombe$x4,anscombe$y4)
# --> 이런 수치만 봐서는 해석이 힘듦
# data visualization 데이터 시각화
install.packages("backports")
library(backports)
library(dplyr)
library(gapminder)
y <- gapminder %>% group_by(year, continent) %>% summarize(c_pop = sum(pop))
View(y)
# R Base Graphic 함수
plot(y$year,y$c_pop)
plot(y$year,y$c_pop, col=y$continent) # 나라별로 색을 다르게 하기 위해 col속성을 이용
plot(y$year, y$c_pop, col = y$continent, pch = c(1:5)) # pch를 사용하여 5가지 모양의 마커를 사용 <1,2,3,4,5마다 마커의 모양이 다르다 생각>
plot(y$year, y$c_pop, col = y$continent, pch = c(1:length(levels(y$continent)))) # 변수를 이용해서 마커의 모양을 사용, level함수는 데이터 뭐있는지 간단히 출력
# 시각화 자료에 대한 설명: 범례
# 첫 번째 인수는 범례를 나타낼 위치, 두 번째 인수는 범례의 내용, 세 번째 인수는 마커 개수, 네 번째 인수는 색상 개수
legend("topleft",legend=5,pch=c(1:5),col=c(1:5))
legend("topleft", legend = levels((y$continent)), pch = c(1:length(levels(y$continent))), col = c(1:length(levels(y$continent))))
# 예시
plot(gapminder$gdpPercap, gapminder$lifeExp, col = gapminder$continent)
legend("bottomright", legend = levels((gapminder$continent)), pch = c(1:length(levels(gapminder$continent))), col = c(1:length(levels(y$continent))))
plot(log10(gapminder$gdpPercap), gapminder$lifeExp, col = gapminder$continent)
legend("bottomright", legend = levels((gapminder$continent)), pch = c(1:length(levels(gapminder$continent))), col = c(1:length(levels(y$continent))))
# ggplot 시각화하기
library(ggplot2)
# geom_point 사용하기
# x는 로그함수를 적용시키고 그래프를 그려라 (색상은 변수를 적는 aes란에 같이 적음)
ggplot(gapminder,aes(x=gdpPercap,y=lifeExp,col=continent))+geom_point()+scale_x_log10()
# size를 이용해서 <마커의 크기를 국가의 인구에 비례하게> 그래프 그리기
ggplot(gapminder, aes(x = gdpPercap, y = lifeExp, col = continent, size = pop)) + geom_point() + scale_x_log10()
# 위처럼 했을 때, 마커들이 서로 중첩되어 가려지는 문제 해결
ggplot(gapminder, aes(x = gdpPercap, y = lifeExp, col = continent, size = pop)) + geom_point(alpha = 0.5) + scale_x_log10()
# 위 시각화 자료를 연도별로 쪼개서 보기
ggplot(gapminder, aes(x=gdpPercap, y=lifeExp, col=continent, size=pop)) + geom_point(alpha=0.5) + scale_x_log10() + facet_wrap(~year)
# geom_bar사용하기
# x축은 country, y축은 pop한 상태에서 pop을 오름차순 정렬하도록 시각화하는데 geom_bar로 시각화하라
gapminder %>% filter(year == 1952 & continent =="Asia") %>% ggplot(aes(reorder(country, pop), pop)) + geom_bar(stat = "identity")
# 위 시각화자료에서 x와 y를 바꿈 <coord_flip함수 이용>
gapminder %>% filter(year == 1952 & continent =="Asia") %>% ggplot(aes(reorder(country, pop), pop)) + geom_bar(stat = "identity") + coord_flip()
# 위 시각화 자료에서 y를 로그 씌워서 시각화
gapminder %>% filter(year==1952 & continent== "Asia") %>% ggplot(aes(reorder(country, pop), pop)) + geom_bar(stat = "identity") + scale_y_log10() + coord_flip()
# geom_point + geom_line 사용하기
# 한국의 기대수명을 geom_poin()를 통해 그래프로 그리기! geom_line을 통해 점에 선을 추가하기
gapminder %>% filter(country == "Korea, Rep.") %>% ggplot(aes(year, lifeExp, col = country)) + geom_point() + geom_line()
# 히스토그램 사용하기
x = filter(gapminder, year == 1952)
hist(x$lifeExp, main = "Histogram of lifeExp in 1952")
x %>% ggplot(aes(lifeExp)) + geom_histogram()
# box_plot 사용하기
x %>% ggplot(aes(continent, lifeExp)) + geom_boxplot()
# box_plot과 시각화 결과 비교하기
ggplot(gapminder,aes(continent,lifeExp))+geom_point(alpha=0.2,size=1.0,position="jitter")
# 시각화 도구
plot(cars,type="p",main="cars") # p는 점으로 시각화
plot(cars,type="l",main="cars") # l는 선으로 시각화
plot(cars,type="b",main="cars") # b는 점과 선으로 시각화
plot(cars,type="h",main="cars") # h는 히스토그램으로 시각화
# mutate는 새로운 변수를 생성하는 함수이다. 즉 x에 gdp변수를 추가한다. 이후 나라와 gdp만 선택하고 내림차순 정렬한 뒤 출력한다.
(x = gapminder %>% filter(year == 1952 & continent == "Asia") %>% mutate(gdp = gdpPercap*pop) %>% select(country, gdp) %>% arrange(desc(gdp)) %>% head())
# pie함수를 통해 원형 시각화
pie(x$gdp, x$country)
# barokit울 통해 막대형 시각화 <names.arg속성으로 무슨 데이터인지 나타냄>
barplot(x$gdp, names.arg = x$country)
x = gapminder %>% filter(year == 2007 & continent == "Asia") %>% mutate(gdp = gdpPercap*pop) %>% select(country, gdp) %>% arrange(desc(gdp)) %>% head()
pie(x$gdp, x$country)
barplot(x$gdp, names.arg = x$country)
# matplot은 다중 플롯을 만드는 함수이다.
matplot(iris[, 1:4], type = "l")
# ity속성을 이용해서 점선을 만든다. 1: 직선, 2: 약간 점선인 직선, 3: 점선인 직선, 4: 많이 점선인 직선
legend("topleft", names(iris)[1:4], lty = c(1, 2, 3, 4), col = c(1, 2, 3, 4))
# 그래프에 색을 적용하기
install.packages("RColorBrewer")
library(RColorBrewer)
display.brewer.all() # 모든 색 보기
# [그림 6-37(a)] : 기본 팔레트를 적용한 그래프: fill속성을 이용함
gapminder %>% filter(lifeExp>70) %>% group_by(continent) %>% summarize(n = n_distinct(country)) %>% ggplot(aes(x = continent, y = n)) + geom_bar(stat = "identity", aes(fill = continent))
# [그림 6-37(b)] : Spectral 팔레트를 적용한 그래프 : fill속성, scale_fill_brewer()함수를 이용함
gapminder %>% filter(lifeExp>70) %>% group_by(year, continent) %>% summarize(n = n_distinct(country)) %>% ggplot(aes(x = continent, y = n)) + geom_bar(stat = "identity", aes(fill = continent)) + scale_fill_brewer(palette = "Spectral")
# 아래는 복습 소스
# [그림 6-43(a)] gdpPercap의 변화 비교
gapminder %>% filter(country == "Kuwait"|country == "Saudi Arabia"|country == "Iraq"|country == "Iran"|country == "Korea, Rep."|country == "China"|country == "Japan") %>% ggplot(aes(year, gdpPercap, col = country)) + geom_point() + geom_line()
# [그림 6-43(b)] pop의 변화 비교
gapminder %>% filter(country == "Kuwait"|country=="Saudi Arabia"|country == "Iraq"|country == "Iran"|country == "Korea, Rep."|country == "China"|country == "Japan") %>% ggplot(aes(year, pop, col=country)) + geom_point() + geom_line()
# [그림 6-43(c)] gdp의 변화 비교
gapminder %>% filter(country == "Kuwait"|country == "Saudi Arabia"|country == "Iraq"|country == "Iran"|country == "Korea, Rep."|country == "China"|country == "Japan") %>% mutate(gdp=gdpPercap*pop) %>% ggplot(aes(year, gdp, col = country)) + geom_point() + geom_line() + scale_y_log10()
북 참고) R로 배우는 데이터 과학