반응형

filter
select
mutate
summarize
arrange

 

#관측치의 개수와 변수의 개수는 각각 몇 개입니까?
summary(airquality)
dim(airquality)
str(airquality)

 

#변수 각각에 대해 최솟값,최대값,중앙값,평균 등의 요약통계량을 한꺼번에 보고싶을때 쓰는 함수는 ?
summary(airquality)

library(dplyr)
#오존이  32q크고 ,바람은 9보다 작은 날은 모두 
airquality %>% filter(Ozone > 32 & Wind <9) %>% summarise(n())

airquality %>% select(Ozone , Wind , Temp , Month) %>% filter(Temp >= 80) %>% arrange(desc(Ozone)) %>%  head()

airquality %>% select(1 , 2 , 3 , 4)

airquality %>% select(1:4)

airquality %>% select(-2)


airquality %>% select(Ozone , Wind , Temp , Month) %>% group_by(Month) %>% summarise(ave= mean(Wind))
# summarise(ave= mean(Wind))
airquality %>% select(Ozone , Wind , Temp , Month) %>% group_by(Month) %>% summarise(ave= max(Wind))
#summarise(avg= mean(Wind))

airquality %>% filter(Wind >= 10) %>% group_by(Month) %>% summarise(avg= mean(Temp))

game <- read.csv("gamedata.csv")   #시간이 오래 걸린다.                                                                             
game


library(data.table)
data<- fread("gamedata.csv")

getwd()

dim(data)

library(readr)

data1 <- read_csv("gamedata.csv")
dim(data1)

head(data1)
summary(data1)

rm(data,data1)
rm(list=ls())

data <- fread("conveniencestore.csv",encoding = "UTF-8")
dim(data)

head(data)

data1 <- read_csv("conveniencestore.csv")#한글이 안깨진다. 알아서 코딩이 다 되여있다.
head(data1)

read.csv() #데이터 적을때 
fread
read_csv()#파일과 관계없이 잘 쓰여진다.

summary(data1)
summary(data)

빈도수  table

data <- sample(4, 29, replace = T)
data
table(data) #빈도수 
hist(data)#histogram
hist(table(data))# 붙어 있고 
barplot(data)
barplot(table(data))# 흩어져있다.
pie(table(data))#데이터를 tableㄹ 만들고 pie
table(data) %>% pie()
data %>% table() %>%  pie()

abline()
x-y평면에   y= a+bx 

저수준->위에 있을때 라인 text글자를 집여있다든지 예:abline() 그림을 그리지 않는다.
고수준->혼자서 그림을 그릴수 있다.

par(mfrow= c(1,1))
x <- c(2,3,2,3)
barplot(x)
fit <- lm(dist~speed, data= cars)
fit
plot(fit)
par(mfrow= c(2,2))
plot(fit)

abline(a= 40, b = 4, col ='red')

lty -> line type
lwd -> line weidth
col->색갈
v->vertical->수직
h->horisental ->수평
legend->범례

 

ggplot2예쁘게 보여주는 것
3.  ggplot2 그래픽 패키지 
ggplot2 패키지를 알아보자 
gg grammer of Graphics
reticulater -> R studio에서 r처럼 사용하는 것
ggplot2
R graphcics cookbook
R science

www.r-graph-gallery.com/

www.ggplot2-exts.org/gallery/

 

더 다양한 시각화 https://plot.ly/r/

plotly는  Interactive 그래프를 그려주는 라이브러리입니다 
Scala, R, Python, Javascript, MATLAB 등에서 사용할 수 있습니다 

시각화를 위해 D3.js를 사용하고 있습니다 
사용해보면 사용이 쉽고, 세렦된 느낌을 받습니다

 

mtcars
str(mtcars)
mtcars$cyl
library(data.frame)
mtcars$cyl <- as.factor(mtcars$cyl)
str(mtcars)

#캐릭터 pch(4,6,8)
plot(mpg ~ hp, data= mtcars, col= cyl, pch=c(4,6,8)[mtcars$cyl], cex=1.2)
legend("topright",legend= levels(mtcars$cyl),pch= c(4,6,8) , col = levels(mtcars$cyl))

library(ggplot2)
ggplot(mtcars, aes(x=hp,y=mpg,color= cyl, shape=cyl))+
  geom_point(size=3)

 

2+3
2단계는 80% 3에서는 30%
1.평면세팅
2.도형선택
3.라벨
4.테마
5.패싯
ggplot라는 부런다.
1.평면세팅 ggplot(data=,aes(x=,y=))
*ggplot(data = 데이터 셋명) 
주요 함수 ggplot(data = 데이터 셋명) : 데이터를 불러오는 역할 
mapping = aes(x = , y =  ) : x축, y축의 꾸미기로 사용한다 
 
geom_function() : 어떤 그래프를 그릴지 정하는 함수 
mapping = aes(항목1=값1, 항목2=값2)                   
: geom_function() 의 옵션으로 꾸미기로 사용한다. 
 
position(x, y), color(색상), fill(채우기), shape(모양), linetype(선 형태), size(크기) 등 
팩터로 바구는 것 

 

mpg
str(mpg)
names(mpg)
ggplot(data = mpg ,aes(x = displ , y = hwy))#단계 배경 설정(측)
ggplot(data = mpg ,aes(x = displ , y = hwy))+ geom_point() #배경에 산정도 추가
ggplot(data = mpg ,aes(x = displ , y = hwy))+ geom_point() + xlim(3,6) #x측 분위 3~6으로 지정
ggplot(data = mpg ,aes(x = displ , y = hwy))+ geom_point() + xlim(3,6) + ylim(10,30) #범주형있을때 색갈이 생긴다.
#여기는 왼쪽으로 모여있다.

#범주데이터 fator 3가지 형태로 바꿔는 것 
ggplot(data= mpg, aes(x = displ, y = hwy, color= drv,shape = drv))+geom_point(size=2)

ggplot(data= mpg, aes(x = displ, y = hwy, color= cty))+geom_point(size=2)

summary(mpg$cty)
 factor하면 범주
ggplot(data = mpg, aes(x = displ, y = hwy)) +geom_point(aes(color= class))

ggplot(data = mpg, aes(x = displ, y = hwy,color= class)) +geom_point(size = 3)
ggplot(data = mpg, aes(x = displ, y = hwy)) +geom_point(aes(color= class), size = 3)

p <- ggplot(data = mpg, aes( x= displ,y= hwy))
p + geom_point(aes(color=class))

q <- geom_point(aes(color = class))
p + q

geom_point  Scatterplot  
geom_bar  Bar plot 
geom_histogram  Histogram  
geom_density  Prabablity distribution plot  
geom_boxplot  Box and whiskers plot  
geom_text  Textual annotations in a plot 
geom_errorbar  Error bars  

 

ggplot(data = mpg, aes(x = displ, y = hwy) )+geom_point(size = 2)
ggplot(data = mpg, aes(x = displ, y = hwy , shape= drv) )+geom_point(size = 2)
ggplot(data= mpg, aes(x = displ, y = hwy, color = drv))+geom_point(size = 2)
ggplot(data= mpg, aes(x = displ, y = hwy, color = drv, shape= drv))+geom_point(size = 2)

ggplot(data = mpg, aes(x = displ, y = hwy) )+geom_point(size = 2)+geom_smooth(method = "lm") #수자 보여준다.
ggplot(data = mpg, aes(x = displ, y = hwy , shape= drv) )+geom_point(size = 2)
ggplot(data= mpg, aes(x = displ, y = hwy, color = drv))+geom_point(size = 3)
ggplot(data= mpg, aes(x = displ, y = hwy, color = drv, shape= drv))+geom_point(size =3)+geom_smooth(method = "lm")

p2 <- ggplot(data= mpg, aes(x= displ, y = hwy, color= drv, shape= drv))+
  geom_point(size = 2)
p2

p2 + geom_smooth(method = "lm")
p2 + geom_smooth(method="lm")+theme_dark()

 

3. 테마 theme

p3 <- ggplot(data= mpg, aes(x= displ, y = hwy, color= drv, shape= drv))+
  geom_point(size = 2)+
  geom_smooth(method= "lm")
p3
p3 + theme_dark() #배경 까막게

p3 <- ggplot(data= mpg, aes(x= displ, y = hwy, color= drv, shape= drv))+
  geom_point(size = 2)+
  geom_smooth(method= "lm")
p3
p3 + theme_dark() #배경 까막게
p3 + theme_bw() # 배경 줄 
p3 + theme_classic() # 아무것도 없음

help(theme_bw)

p3 + theme_gray() #배경 grey
p3 + theme_linedraw() #line 걸어짐
p3 + theme_light() #선 연하게 
p3 + theme_minimal()#테두리 없어짐
p3 + theme_void()
p3 + theme_test()

r은 in  memory 방식이기때문에 늦다.

install.packages("ggthemes")
library(ggthemes)
?ggthemes
p2 + theme_wsj() # 오랜지 등
p2 + theme_economist() #색상 연두색
p2 + theme_excel_new() # 엑셀처럼
p2 + theme_fivethirtyeight()# 
p2 + theme_solarized_2()
p2 + theme_stata()

 

4. 라벨 

ggplot( data = mpg, aes(x= displ, y = hwy , color = drv , shape = drv))+
  geom_point(size = 2)+
  geom_smooth(method= "lm")+
  labs(title = "<배기량에 따른 고속도로 연비 비교>", x ="배기량", y ="연비" )

 

5. facet
#면 분할 하은 방법
d <- ggplot(mpg, aes(x = displ, y = hwy , color = drv)) + 
  geom_point()
d
d + facet_grid(drv ~ .) #div로 3개로 분할한다.
d + facet_grid(. ~ cyl) #cyl 에 의해서 분할하는 데 열로 분할하라 
d + facet_grid(drv ~ cyl)

d + facet_grid( ~ class)
d + facet_wrap( ~ class) #정렬

d + facet_wrap( ~ class, nrow = 2) #행의 개수
d + facet_wrap( ~ class, ncol = 4) #열의 개수

ggplot(data = mpg, aes( x= displ, y = hwy, color = drv))+
  geom_point(size = 2)
ggplot(data = mpg, aes(x = displ, y = hwy, color = drv))+
  geom_point(size = 2, position = "jitter")
dplyr :: glimpse(mpg)
jitter는 모호하게 하는 것이다 값이 거의 최적화 댈때 뭉갠다.

 

geom_point  Scatterplot  
geom_bar  Bar plot 
geom_histogram  Histogram  
geom_density  Prabablity distribution plot  
geom_boxplot  Box and whiskers plot  
geom_text  Textual annotations in a plot 
geom_errorbar  Error bars  오차 바

 

p1 <- ggplot(data= mpg, aes( x= displ, y = hwy , color = drv))
p1 + geom_point(size =2 )
p1+ geom_line() #라인으로 연결
p1 + geom_point(size =2) +geom_line()

hist는 붙어있고  연속변수 
막대그래프는 이상변수 떨어져있다.

ggplot( data = mpg, aes( x= displ)) +geom_bar()#y 없을 때 count
ggplot( data = mpg, aes( x= displ, fill = factor(drv))) + geom_bar()
ggplot( data = mpg, aes( x= displ, fill = factor(drv))) +geom_bar(position = "dodge")

 

#비율로
ggplot( data = mpg, aes( x = displ, fill = factor(drv))) + geom_bar(position = "fill")
ggplot( data = mpg, aes ( x = displ, fill = factor(drv))) + geom_bar(position= "fill")+facet_wrap(~class)#나누어서 

ggplot( data = mpg, aes( x = displ))+ geom_histogram()
ggplot( data = mpg, aes( x= displ))+ geom_histogram(fill= "blue")
ggplot( data = mpg, aes( x= displ))+ geom_histogram(fill = "blue", binwidth = 0.1) #쫍아졌다.

 

library(ggplot2)
library(dplyr)
plot(mtcars)
attach(mtcars)#변수를 쓰겠다.
mtcars
wt
disp
plot(wt) #기본함수  x와 y 에 대한 것에 
mpg
plot(wt, mpg)
plot(wt, mpg, main="wt와 mpg의 관계계")
plot(wt, disp, mpg)#Error in plot.xy(xy, type, ...) : 유효한 플랏 타입이 아닙니다

library(scatterplot3d)
scatterplot3d(wt, disp, mpg, main ="3D sactter plot")
scatterplot3d(wt, disp, mpg, pch = 15, highlight.3d = TRUE, type ="h", main = "3D sactter plot" )

library(rgl)
plot3d(wt, disp, mpg)
plot3d(wt, disp, mpg , main = "wt vs mpg vs disp" , col ="red" , size = 10)

시각화중급

Boxplot
Scatterplot
Densityplot


box plot-데이터 분포도 알 수 있음 최소갓 최대값 중앙값->어디에 몰려있는지
abc <- c(110 , 300, 150, 280, 310)
def <- c(180, 200, 210, 190, 170)
ghi <- c(210, 150, 260, 210, 70)
boxplot(abc,def,ghi)

 

# col: 상자내부의색지정 
# names: 각막대의이름지정 
# range: 막대의끝에서수염까지의길이를지정 
# width: 박스의폭을지정 
# notch: TRUE이면상자의허리부분을가늘게표시 
# horizontal: TRUE이면상자를수평으로그림

 

5가지 요약 수치 사용

abc <- c(110 , 300, 150, 280, 310)
def <- c(180, 200, 210, 190, 170)
ghi <- c(210, 150, 260, 210, 70)
boxplot(abc,def,ghi)
boxplot(abc,def,ghi, col= c("yellow","cyan","green"),name =c("BaseBall","SoccerBall","BaseBall"),horizontal=T)
summary(abc)
summary(def)
summary(ghi)

head(iris)
ggplot(iris, aes(x= Sepal.Length, y = Sepal.Width))+geom_point()

ggplot(iris, aes(x= Sepal.Length, y = Sepal.Width))+geom_point(color="red",fill ="blue",shape = 21, alpha = 0.5, size= 6, stroke = 2)
#alpha투명도 
#stroke 안에 동그라미테두리

ggplot(iris, aes( x = Sepal.Length, y = Sepal.Width, color = Species,shape= Species))+geom_point(size = 6, alpha = 0.5)
ggplot(iris, aes( x = Sepal.Length, y = Sepal.Width, color = Species,shape= Species))+geom_point(size = 3, alpha = 0.5)

data = head(mtcars,30)
ggplot(data,aes(x= wt, y = mpg))+geom_point()+geom_text(label= rownames(data),nudge_x = 0.25, nudge_y = 0.25,check_overlap = T)
#check_overlap겹치느나 안겹치느내
#nudge_x 동그라미 와 오른쪽 거리 
#nudge_y 동그라미와 위거리 

ggplot(data, aes(x = wt, y = mpg)) +geom_label(label = rownames(data),nudge_x = 0.25, nudge_y = 0.2)
#텍스트 둘래 박스 쳐준다.

ggplot(data, aes(x = wt, y = mpg,fill= cyl)) +geom_label(label = rownames(data),color="white",size= 5)
#박스와 다르다.

ggplot(data= iris, aes(x = Sepal.Length, y = Sepal.Width))+geom_point()+geom_rug(col= "steelblue",alpha = 0.1 , size = 1.5)
#테두리 가에 있는 것
#농도가 진해지면 수치가 많다. 분포
library(ggplot2)
install.packages("ggExtra")
library(ggExtra)
head(mtcars)
mtcars
mtcars$wt = as.factor(mtcars$wt)
mtcars$cyl = as.factor(mtcars$cyl)
mpg = as.factor(mpg)
str(mtcars)
ggplot(mtcars, aes(x = wt, y = mpg, color= cyl, size = cyl))+geom_point()+theme(legend.position = "none")
#legend.position = "none" 범례를 안보이게 하기 
ggplot(mtcars, aes(x = wt, y = mpg, color= cyl, size = cyl))+geom_point()
p <- ggplot(mtcars, aes(x = wt, y = mpg, color= cyl, size = cyl))+geom_point()+theme(legend.position = "none")
ggMarginal(p, type="histogram") #이력
ggMarginal(p, type="density") # 선
ggMarginal(p, type="boxplot") # boxplot
ggMarginal(p, type ="histogram", size = 10)#size 조정
ggMarginal(p, type = "histogram", fill="slateblue", xparams = list(bins= 10),yparams = list(bins = 10))

www.r-graph-gallery.com/

정지된것 은   plot
움직이는것 볼 수 있는 것은 창에서 

 

data = data.frame(cond = rep(c("condition_1","condition_2"),each= 10), my_x = 1:100 +rnorm(100, sd= 9),my_y = 1:100 +rnorm(100,sd= 16))
data
#rep(c("condition_1","condition_2"),each= 10) 10번씩
#표준편차 sd
#정교분포
ggplot(data,aes( x= my_x, y = my_y))+geom_point(shape= 1)

 

#lm 직선 overfitting  
#se= T는 오류편차 주지 말라고 하는 것 범윌ㄹ 안아렬주고 대충알려준다.
ggplot(data, aes(x= my_x, y = my_y))+geom_point(shape= 1) +geom_smooth(method = lm, color="red" ,se= F)
ggplot(data, aes(x= my_x, y = my_y))+geom_point(shape= 1) +geom_smooth(method = lm, color="red" ,se= T)

a = seq(1,29)+4 * runif(29,0.4)
#runif 0~0.1
b = seq(1,29) ^ 2 +runif(29, 0.98)
library(dyplyr)
par(mfrow=c(2,2))#분할 로 해서 4개 그림 그린다.

plot(a,b, pch= 20)
plot(a-b, pch =18)
hist(a, border= F, col = rgb(0.2,0.2,0.8,0.7),main="")
#투명도 0.7
# 0.2 red 0.2 green 0.8 blue
boxplot(a, col ="grey", xlab="a")

install.packages("rattle")
library(rattle)
Temp3pm
cities <- c("Canberra","Darwin","Melbourne","Sydney")
ds <- subset(weatherAUS,Location %in% cities & !is.na(Temp3pm))#Location %in% cities합쳐주는 
p <- ggplot(ds, aes(Temp3pm, colour = Location, fill= Location))
p <- p_geom_denisity(alpha - 0.55)
p
View(weatherAUS)
# %in%속해있는지 
#subset(weatherAUS,Location %in% cities & !is.na(Temp3pm)) 행과열을 추출하는 것이다.

subset(weatherAUS,Location %in% cities & !is.na(Temp3pm))

data(diamonds)
head(diamonds)

ggplot(data = diamonds , aes(x = price, group = cut, fill= cut))+geom_density(adjust = 1.5)
ggplot(data = diamonds , aes(x = price, group = cut, fill= cut))+geom_density(adjust = 5)
#가격에 대해서 예상 이런조건이면 

ggplot(data = diamonds, aes(x= price, group = cut, fill= cut))+ geom_density(adjust = 1.5, alpha= 0.2)
ggplot(data = diamonds, aes( x= price, group = cut, fill= cut))+ geom_density(adjust = 1.5, position = "fill")#누적되서 나타나는 것
x1 = rnorm(100)
x2 = rnorm(100, mean = 2)
par(mfrow = c(2,1))

par(mar = c(0,5,3,3))
plot(density(x1),main="",xlab = "", ylim = c(0,1),xaxt = "n", las = 1, col = "slateblue1", lwd = 4)
par(mar= c(5,5,0,3))
plot(density(x2), main ="", xlab ="Value of my variable", ylim=c(1,0), las = 1, col="tomato3", lwd = 4)


diamonds
ggplot(data = diamonds , aes(x = depth, group = cut, fill= cut))+geom_density(adjust = 1.5)


data <- data.frame(name = c("north","south","south-east","north-west","south-west","north-east","west","east"),val=sample(seq(1,10),8))
data
mpg

install.packages("forcats")
library(forcats)
library(dplyr)
data %>% mutate(name = fct_reorder(name,val)) %>% ggplot(aes(x=name, y = val))+
  geom_bar(stat= "identity")+
  coord_flip() #오름차순 

data %>% mutate(name = fct_reorder(name, desc(val))) %>% ggplot(aes(x= name, y = val))+
  geom_bar(stat= "identity")+
  coord_flip() #desc 내름차순 

data <- data.frame(name = letters[1:5], value= sample(seq(4,15),5), sd = c(1,0.2,3,2,4))
ggplot(data) + geom_bar(aes(x= name, y = value), stat ="identity", fill ="skyblue", alpha= 0.7)+
  geom_errorbar(aes(x = name,ymin = value-sd, ymax = value+sd),width = 0.4 , colour ="orange", alpha = 0.9, size = 1.3)

ggplot(data)+
  geom_bar(aes(x= name, y = value), stat ="identity", fill ="skyblue", alpha = 0.5)+
  geom_crossbar(aes(x = name, y = value, ymin = value-sd , ymax = value+sd ), width = 0.4 , colour="orange", alpha = 0.9, size = 1.3)



ggplot(data)+
  geom_bar(aes(x= name, y = value), stat ="identity", fill ="skyblue", alpha = 0.5)+
  geom_linerange(aes(x = name, ymin = value-sd , ymax = value+sd ), width = 0.4 , colour="orange", alpha = 0.9, size = 1.3)

ggplot(data)+
  geom_bar(aes(x= name, y = value), stat ="identity", fill ="skyblue", alpha = 0.5)+
  geom_errorbar(aes(x = name, ymin = value-sd , ymax = value+sd ), width = 0.4 , colour="orange", alpha = 0.9, size = 1.3)+coord_flip()

 

반응형

'Study > R' 카테고리의 다른 글

R-6  (0) 2020.09.05
R-5  (0) 2020.09.05
R-4  (0) 2020.09.05
R -2  (0) 2020.09.05
R-1  (0) 2020.09.02

+ Recent posts