sf
パッケージのread_sf()
関数でシェープファイルを読み込む。属性 | コード |
---|---|
都道府県名 | (N03_001) |
北海道の振興局名 | (N03_002) |
郡名 | (N03_003) |
市区町村名 | (N03_004) |
政令指定都市の行政区域名 | (N03_005) |
全国地方公共団体コード | (N03_007) |
## N03_001 to pref
names(ishikawa)[names(ishikawa) == "N03_001"] <- "pref"
## N03_002 to hokkaido
names(ishikawa)[names(ishikawa) == "N03_002"] <- "shinko"
## N03_003 to gun
names(ishikawa)[names(ishikawa) == "N03_003"] <- "gun"
## N03_004 to city
names(ishikawa)[names(ishikawa) == "N03_004"] <- "city"
## N03_005 to ku
names(ishikawa)[names(ishikawa) == "N03_005"] <- "ku"
## N03_007 to code
names(ishikawa)[names(ishikawa) == "N03_007"] <- "code"
# cityとcodeの抽出
city <- list(city = ishikawa$city, code = ishikawa$code)
# データフレームに変換
city <- data.frame(city)
# 重複の確認
duplicates <- duplicated(city[, c("city", "code")])
# 重複の削除
city <- city[!duplicates, ]
# データの確認
city
# 震度データの読み込み
library(readxl)
ishikawa_data <- read_excel("ishikawa_data.xlsx")
ishikawa_data$city <- NULL
# shindoがNAの場合は、NAを"記録なし"に変換
#ishikawa_data$shindo[is.na(ishikawa_data$shindo)] <- "記録なし"
# ishikawa_simpleにishikawa_dataを接続
ishikawa_simple <- merge(ishikawa_simple, ishikawa_data, by = "code")
# 石川県の市町村をggplot2でプロットする。
library(ggplot2)
ggplot(ishikawa_simple) + # ishikawa_simpleを使ってプロット
geom_sf(aes(fill = city), color = "white") + # 塗りつぶしの色をcityに設定
scale_fill_viridis_d() + # 塗りつぶしの色をviridisパレットに設定
theme_minimal() + # テーマをminimalに設定
theme(legend.position = "bottom") + # 凡例を下部に表示
labs(title = "石川県の市町村地図", # タイトルを設定
fill = "市町村名") # 凡例のタイトルを設定
TRUE
geom_sf_text()
関数の position
引数には、テキストを配置する方法を指定するオプションがある。
# 石川県の市町村をggplot2でプロットする。
library(ggplot2)
ggplot(ishikawa_simple) + # ishikawa_simpleを使ってプロット
geom_sf(aes(fill = pref), color = "white") + # 塗りつぶしの色わけをprefに設定
geom_sf_text(data = ishikawa_simple,
aes(label = city), size = 2, color = "black",
position = "dodge") + # ラベルをcityに設定
theme_minimal() + # テーマをminimalに設定
labs(title = "石川県の市町村地図") + # タイトルを設定
theme(axis.title.x = element_blank()) + # x軸のタイトルを非表示
theme(axis.title.y = element_blank()) + # y軸のタイトルを非表示
theme(axis.text.x = element_blank()) + # x軸の目盛りを非表示
theme(axis.text.y = element_blank()) # y軸の目盛りを非表示
TRUE
# 石川県の市町村をggplot2でプロットする。
library(ggplot2)
ggplot(ishikawa_simple) + # ishikawa_simpleを使ってプロット
geom_sf(aes(fill = shindo), color = "white") +
scale_fill_viridis_d(option = "D") +
geom_sf_text(data = ishikawa_simple,
aes(label = city), size = 2, color = "white",
position = "dodge") + # ラベルをcityに設定
theme_gray() + # テーマをminimalに設定
theme(legend.position = "bottom") + # 凡例を下部に表示
labs(title = "石川県の市町村地図", # タイトルを設定
fill = "市町村名") # 凡例のタイトルを設定
TRUE
# 石川県の市町村をggplot2でプロットする。
# shindo2 = 0の場合、NAに変換
ishikawa_simple$shindo2[ishikawa_simple$shindo2 == 0] <- NA
# shindo2で主題図を作成
# 色の指定のため
library(RColorBrewer)
library(ggplot2)
ggplot(ishikawa_simple, aes(fill = shindo2)) +
geom_sf() +
scale_fill_gradientn(colors=brewer.pal(9,"GnBu"),
na.value = "white")+
theme_gray (base_family = "HiraKakuPro-W3")+
labs(fill = "震度")+
ggtitle("能登半島沖地震の震度")
TRUE