R studios

R통계 : Theme #9. ggmap ( Thanks to Google)

Frisbeen 2024. 5. 27. 17:03

 

 

특정 지역 중심의 지도를 출력

map = get_googlemap(center = c(123.124144,37.124124)
,maptype ="roadmap",zoom=17,size=c(320,320) size가 작아질수록
ggmap(map, extent ="device") > 지도 여백 설정(이건 여백이 없는 것)

주소를 이용하여 지도 출력 (geocode의 힘을 빌리자)

gc= geocode(enc2utf8("호미곶")) or ("Tokyo, Japan) 해도 되고 다양하게..
lonlat = c(gc$lon, gc$lat) 
map = get_googlemap(center = lonlat)
ggmap(map)

# 마커까지 넣고 싶다면?
map = get_googlemap(center = lonlat,marker = gc)

엑셀파일에서 가져와서 지도를 그릴때

  1. 경도 위도 값을 알아서 센터를 설정해줘야함
earthquake = read.xlsx(file.choose(),sheet = 1, startRow = 4)
# 특정한 데이터에 ex) 35N 여기서 N 같은 부분 문자 제외하기 (경도 위도 다루기)

# 6,7번째 열에 위도 & 경도 값들이 있다. 근데 N , S가 너무너무 방해돼 
earthquake[,6] = gsub("N","",earthquake[,6])
earthquake[,7] = gsub("E","",earthquake[,7])

# 필요한 정보인 위도와 경도 & 규모만 따로 가지고와서 데이터 프레임을 만들어준다.
earthquake_processed = data.frame(lon =earthquake[,7], 
lat = earthquake[,6],mag=earthquake[,3])

# structure 확인해서 숫자인 값이 문자로 되어있으면 다시 숫자로 바꿔주기
earthquake_processed[,1] = as.numeric(as.character(earthquake_processed[,1]))
earthquake_processed[,2]= as.numeric(as.character(earthquake_processed[,2]))

#센터 설정 (웬만하면 중간값, max+min/2 of lon, lat) 이 순서로
center = c((max(earthquake_processed$lon)+min(earthquake_processed$lon))/2, 
          (max(earthquake_processed$lat)+min(earthquake_processed$lat))/2)
          
          
 #지도 그리기
 map = get_googlemap(center = center, zoom =6 )gmap =ggmap(map)
 
 # 점 찍기
 gmap + geom_point(data = earthquake_processed,aes(x=lon,y=lat),
 color="red",size=earthquake_processed$mag,alpha=0.5)

geocode로 직접 가져오기 →center = colMeans(gc) 이게 직빵

## data processing
#europe이라는 데이터의 숫자에 쓸데없이 ,가 너무 많이 붙여있어서 없애는건 gsub으로 꼼짝못해
europe $ gdp = gsub(",","",europe$gdp)
europe $ gdp = as.numeric(as.character(europe$gdp))

#geocode함수로 위도경도 가져오면 자동적으로 데이터프레임화 시켜주는데 이때 lon,lat 열이 만들어짐
gc= geocode(europe$name)

# gc $lon, gc$ lat 활용해서.. 데이터프레임 새거 만들고
processedEurope= data.frame(city = europe $name, lon = gc$lon ,lat = gc$lat,
 gdp = europe $gdp)
 
 # 센터 설정은 그냥 colmeans(gc) 떄려버리고
 center = colMeans(gc)
 # map 센터를 확실히 만들고
 map = get_googlemap(center = center, zoom =4 , scale = 2, size=c(640,640), 
 maptype = "hybrid")
 gmap = ggmap(map)
 gmap + geom_point(data = processedEurope, aes(x=lon,y=lat),color="red",
 size =processedEurope$gdp/1000000,alpha=0.5)