Graphics Reference
In-Depth Information
# Transform the USArrests data set to the correct format
crimes <- data.frame(state = tolower(rownames(USArrests)), USArrests)
crimes
state Murder Assault UrbanPop Rape
Alabama alabama
13.2
236
58 21.2
Alaska alaska
10.0
263
48 44.5
Arizona arizona
8.1
294
80 31.0
...
West Virginia west virginia
5.7
81
39 9.3
Wisconsin wisconsin
2.6
53
66 10.8
Wyoming wyoming
6.8
161
60 15.6
library(maps) # For map data
states_map <- map_data( "state" )
# Merge the data sets together
crime_map <- merge(states_map, crimes, by.x = "region" , by.y = "state" )
# After merging, the order has changed, which would lead to polygons drawn in
# the incorrect order. So, we sort the data.
head(crime_map)
region long lat group order subregion Murder Assault UrbanPop Rape
alabama -87.46201 30.38968
1
1
< NA >
13.2
236
58 21.2
alabama -87.48493 30.37249
1
2
< NA >
13.2
236
58 21.2
alabama -87.95475 30.24644
1
13
< NA >
13.2
236
58 21.2
alabama -88.00632 30.24071
1
14
< NA >
13.2
236
58 21.2
alabama -88.01778 30.25217
1
15
< NA >
13.2
236
58 21.2
alabama -87.52503 30.37249
1
3
< NA >
13.2
236
58 21.2
library(plyr) # For arrange() function
# Sort by group, then order
crime_map <- arrange(crime_map, group, order)
head(crime_map)
region long lat group order subregion Murder Assault UrbanPop Rape
alabama -87.46201 30.38968
1
1
< NA >
13.2
236
58 21.2
alabama -87.48493 30.37249
1
2
< NA >
13.2
236
58 21.2
alabama -87.52503 30.37249
1
3
< NA >
13.2
236
58 21.2
alabama -87.53076 30.33239
1
4
< NA >
13.2
236
58 21.2
alabama -87.57087 30.32665
1
5
< NA >
13.2
236
58 21.2
alabama -87.58806 30.32665
1
6
< NA >
13.2
236
58 21.2
Once the data is in the correct format, it can be plotted ( Figure 13-35 ), mapping one of the
columns with data values to fill :
Search WWH ::




Custom Search