data analysis & visualization

[ggplot2] 시각화 정리

R2019. 12. 8. 00:48

ggplot(data, aes(x축, y축, fill=범주))

geom_bar : 바 그래프

geom_point : 산점도

geom_line : 라인 그래프

geom_count: 버블차트

geom_label: 라벨 입력

geom_errorbar: 에러 바

ggtitle : 그림제목

coord_flip : 가로 막대그래프로 변경

theme(panel.background = element_rect(fill= "transparent"))

theme_classic()

 

facet_grid, facet_wrap : 면 분할

xlim : x축의 범위

ylim : y축의 범위

 

예제1

data(iris)
del=data.table::setDT(iris)[,.(mean=mean(Sepal.Length)),'Species']
del=reshape2::melt(del,'Species')
library(ggplot2)
ggplot(del,aes(Species,value,fill=factor(Species)))+geom_bar(stat='identity')+
  theme_classic()+theme(plot.title=element_text(face='bold',size=40),
                        legend.box.just = 'right',legend.margin = margin(6,6,6,6))+
labs(fill='Species')+ggtitle('뭐냐')

예제2

ggplot(Cars93, aes(x=Weight, y=MPG.highway,colour=MPG.highway)) +
  geom_point() +scale_colour_gradient(low='lightyellow', high='red',limits=c(20,30))+
  facet_grid(Origin ~ Type)+ggtitle('ggplot 예제')+theme(plot.title=element_text(face='bold',size=30))+
labs(
     subtitle = 'The sub title',
     x = 'x', y = 'y', color = 'colors')+xlim(c(0,4000))+ylim(c(20,40))

 

예제2

 

ggplot2::fortify에 대한 에러 발생한 경우

library(rgdal) 
shp=readOGR('C:/Users/USER/Desktop/CJ/shp/CTPRVN_201703/TL_SCCO_CTPRVN.shp',encoding = 'UTF-8') 
crs=proj4string(shp) 
shp=spTransform(shp,CRS('+init=epsg:4326')) 
set.seed(1) 
temp=data.frame(id=shp@data$CTP_KOR_NM,random=sample(1:1000,length(shp@data$CTP_KOR_NM)),stringsAsFactors = F) 
library(ggmap) 
head(shp@data) 
shp2=fortify(shp,region='CTP_KOR_NM') 

shp3=dplyr::left_join(shp2,temp,'id') 
register_google(key=키) 
location=geocode('대한민국') 
map=get_googlemap(center = unlist(location),zoom=5) 
ggmap(map)+geom_polygon(data=shp3,aes(x=long,y=lat,group=group,fill=random))+scale_fill_gradient(limits=c(250,750)) 

bar plot 의 xlim이 0보다 크게 시작할 때   coord_cartesian(ylim = c(.6, 1),xlim=c(0,24))를 써 해결하면 된다.

 

'R' 카테고리의 다른 글

딥로또 R 버전  (0) 2020.02.10
R 스케줄링  (0) 2020.01.19
[R][SQL] RMariaDB 외부 접속 설정하기  (0) 2019.11.29
[공간정보오픈플렛폼]위경도 변환, 주소 변환  (0) 2019.11.27
[ggmap] pie chart 그리기 예제  (0) 2019.11.26