18, ส.ค. 2020
R-studio : ( EP#20 ) ตกแต่งสัญลักษณ์ 25 ลุ่มน้ำ shapefile ด้วย Unique Value ในโปรแกรม R

R-studio : ( EP#20 ) ตกแต่งสัญลักษณ์ 25 ลุ่มน้ำ shapefile ด้วย Unique Value ในโปรแกรม R 
EP#20: การตกแต่งสัญลักษณ์ลุ่มน้ำทั้ง 25 ลุ่มน้ำของไทยใน R ด้วยการใช้ค่าคุณลักษณะ (Unique Value) ถือเป็นพื้นฐานของการทำ thematic mapping ในระบบ GIS ด้วยภาษา R โดยเฉพาะเมื่อใช้ร่วมกับ shapefile และ การจัดการตาราง attribute ในลักษณะ categorical symbology

เป็นบทเรียนรู้ดึง shapefile 25 ลุ่มน้ำของไทย มาแสดงผล ในรูปแบบ Unique Value ด้วยการใช้ชื่อลุ่มน้ำมาเป็นตัวแสดงผลข้อมูลได้ ด้วยโปรแกรม R

มีเทคนิคพิเศษ การใช้ Excel ในการแปลงข้อมูลชื่อลุ่มน้ำ มาใส่ใน R script ได้สะดวกขึ้น

ลงทะเบียนเพื่อขอตัวอย่างไฟล์ R script ได้ที่  

https://drive.google.com/file/d/1NUuCvMqk7imv-GYDm24m6e6g4mZkXFxS/view?usp=sharing

💡 แนวคิดหลัก

  • ใช้ Shapefile ของ 25 ลุ่มน้ำหลักของประเทศไทย
  • ใช้ ชื่อลุ่มน้ำ เป็น field สำหรับแสดงผลแผนที่ด้วยสีที่แตกต่างกัน (unique value)
  • ตกแต่งสีด้วย Color Palette (จาก RColorBrewer หรือกำหนดเอง)
  • แสดงผลใน Leaflet หรือ ggplot2 ตามความต้องการ

🛠️ ตัวอย่างการทำใน R

1. นำเข้า Shapefile

rCopyEditlibrary(sf)
library(tmap)

# อ่าน shapefile ลุ่มน้ำ
basin <- st_read("TH_Basin_25.shp")

2. ตรวจสอบข้อมูลชื่อลุ่มน้ำ

rCopyEditunique(basin$BASIN_NAME)

💡 เทคนิค: ถ้า BASIN_NAME เป็นภาษาไทยหรือมีปัญหา encoding ให้ใช้ iconv() หรือแก้ใน Excel แล้วเชื่อมใหม่ใน R


3. สร้าง thematic map ด้วย tmap

rCopyEditlibrary(RColorBrewer)

tmap_mode("view") # หรือ "plot" สำหรับ static
tm_shape(basin) +
  tm_polygons("BASIN_NAME",
              palette = "Set3",
              title = "ลุ่มน้ำหลักของไทย") +
  tm_layout(legend.outside = TRUE)

📊 เทคนิคเสริม: การใช้ Excel ช่วยสร้าง Color Mapping

  1. สร้างตารางสีใน Excel:
BASIN_NAMECOLOR
เจ้าพระยา#1f77b4
ป่าสัก#ff7f0e
แม่กลอง#2ca02c
  1. นำเข้าและ merge เข้ากับ shapefile:
rCopyEditcolors_df <- read.csv("basin_colors.csv")
basin <- merge(basin, colors_df, by = "BASIN_NAME")
  1. ใช้ tm_fill พร้อม col ที่กำหนดเอง:
rCopyEdittm_shape(basin) +
  tm_fill(col = "COLOR", title = "ลุ่มน้ำ", alpha = 0.7)

🌐 ส่งออก HTML Map

rCopyEditlibrary(leaflet)
pal <- colorFactor(palette = "Set3", domain = basin$BASIN_NAME)

leaflet(basin) %>%
  addTiles() %>%
  addPolygons(color = ~pal(BASIN_NAME),
              popup = ~BASIN_NAME,
              weight = 1) %>%
  addLegend("bottomright", pal = pal, values = ~BASIN_NAME,
            title = "ลุ่มน้ำ")

📥 ดาวน์โหลดไฟล์ตัวอย่าง

🎓 ลิงก์ R Script + Shapefile:
Google Drive: R script EP#20

ใส่ความเห็น

Related Posts