2015-04-01 120 views
0

輸入:繪製美國熱圖與文字

Percent.Turnout US.State 
70    CA 
80    NM 
76    RI 

我會爲每個在美國50個州的數據。此外,US.State的州名縮寫符合功能狀態中的縮寫.abb

我想要創建一個美國地圖,其中Percent.Turnout印在每個州上。此外,使用ColorBrewer軟件包,我想根據相對於其他狀態的Percent.Turnout對每個狀態進行着色。

我不是很熟悉ggplot語法,所以在基礎R建議,將不勝感激(如果可行的話)

enter image description here

回答

1

如果您想使用ggplot2,那麼你所需要的重大的事情要做的是將狀態縮寫欄以小寫形式映射到完整狀態名稱(爲此,您可以使用state.name,但請確保在其上應用tolower()以獲得正確的格式)。

從那裏開始,只需將您的數據集加入州的地理空間信息並繪製數據即可。

# First, we need the ggplot2 library: 
> library(ggplot2) 
# We load the geospatial data for the states 
# (there are more options to the map_data function, 
# if you are intrested in taking a look). 
> states <- map_data("state") 
# Here I'm creating a sample dataset like yours. 
# The dataset will have 2 columns: The region (or state) 
# and a number that will represent the value that you 
# want to plot (here the value is just the numerical order of the states). 
> sim_data <- data.frame(region=unique(states$region), Percent.Turnout=match(unique(states$region), unique(states$region))) 
# Then we merge our dataset with the geospatial data: 
> sim_data_geo <- merge(states, sim_data, by="region") 
# The following should give us the plot without the numbers: 
> qplot(long, lat, data=sim_data_geo, geom="polygon", fill=Percent.Turnout, group=group) 

這是代碼段的上面的輸出:下面的代碼段一步帶你穿越這一步

enter image description here

現在,你說你想也將值Percent.Turnout添加到地圖。在這裏,我們需要找到各個州的中心點。您可以從我們上面檢索到的地理空間數據(在states數據框中)計算出來,但結果看起來不會很令人印象深刻。值得慶幸的是,R具有在已經計算出我們國家的中心值,我們可以利用的是,如下所示:

# We'll use the state.center list to tell us where exactly 
# the center of the state is. 
> snames <- data.frame(region=tolower(state.name), long=state.center$x, lat=state.center$y) 
# Then again, we need to join our original dataset 
# to get the value that should be printed at the center. 
> snames <- merge(snames, sim_data, by="region") 
# And finally, to put everything together: 
> ggplot(sim_data_geo, aes(long, lat)) + geom_polygon(aes(group=group, fill=Percent.Turnout)) + geom_text(data=snames, aes(long, lat, label=Percent.Turnout)) 

這是最後一條語句的輸出上面:

enter image description here

+0

精彩回答!我遇到的一個小問題是加利福尼亞州和科羅拉多州以及其他一些州內有一些空白空白。你會知道這是爲什麼嗎? – Zslice 2015-04-01 07:06:04

+0

您能否顯示您所看到的截圖?你描述的差距是否與本圖像中的任何區域相匹配(http://www.thisisthegreenroom.com/wordpress/wp-content/uploads/2009/11/maps-package.PNG)?如果是,那麼可能由於某種原因,「州」數據集缺少一些子區域。 – szabad 2015-04-01 15:33:01

+0

我添加了一個截圖作爲編輯我的問題。有兩個相當大的差距突出。 – Zslice 2015-04-03 07:41:43