2015-06-27 159 views
0

我使用以下代碼製作this plotggplot2:scale_fill_brewer自定義標籤

library(XML) 
library(ggplot2) 
library(scales) 
library(plyr) 
library(maps) 

unemp <- 
    readHTMLTable('http://www.bls.gov/web/laus/laumstrk.htm', 
       colClasses = c('character', 'character', 'numeric'))[[2]] 

names(unemp) <- c('rank', 'region', 'rate') 
unemp$region <- tolower(unemp$region) 

us_state_map <- map_data('state') 
map_data <- merge(unemp, us_state_map, by = 'region') 

map_data <- arrange(map_data, order) 

states <- data.frame(state.center, state.abb) 

p1 <- ggplot(data = map_data, aes(x = long, y = lat, group = group)) 
p1 <- p1 + geom_polygon(aes(fill = cut_number(rate, 5))) 
p1 <- p1 + geom_path(colour = 'gray', linestyle = 2) 
p1 <- p1 + scale_fill_brewer('Unemployment Rate (Jan 2011)', palette = 'Set1') 
p1 <- p1 + coord_map() 
p1 <- p1 + geom_text(data = states, aes(x = x, y = y, label = state.abb, group = NULL), size = 2) 
p1 <- p1 + theme_bw() 
p1 

我想要一些操作後,顯示scale_fill_brewer自定義標籤像100或1000。每個標籤後乘以任何幫助將得到高度讚賞。謝謝

回答

3

雖然ggplot幫助函數很方便,但我更喜歡在繪圖習語之外進行數據處理。它使用cut添加1%打破了自定義標籤,並且還採用了適當的美國投影和具有連續彩色規模遠遠更適合這個數據和(最終)刪除一噸圖表垃圾:

library(XML) 
library(ggplot2) 
library(scales) 
library(plyr) 
library(maps) 
library(ggthemes) 

unemp <- 
    readHTMLTable('http://www.bls.gov/web/laus/laumstrk.htm', 
       colClasses = c('character', 'character', 'numeric'))[[2]] 

names(unemp) <- c('rank', 'region', 'rate') 
unemp$region <- tolower(unemp$region) 

# gain granular control of the breaks outside of ggplot 
unemp$brk <- cut(unemp$rate, 0:9, labels=c("0%", sprintf("≥%d%%", 1:8))) 

head(unemp) 
## rank  region rate brk 
## 1 1  nebraska 2.6 ≥2% 
## 2 2 north dakota 3.1 ≥3% 
## 3 3   utah 3.5 ≥3% 
## 4 4  vermont 3.6 ≥3% 
## 5 5   iowa 3.8 ≥3% 
## 6 5 minnesota 3.8 ≥3% 

us_state_map <- map_data('state') 
map_data <- merge(unemp, us_state_map, by = 'region') 

map_data <- arrange(map_data, order) 

states <- data.frame(state.center, state.abb) 

p1 <- ggplot(data = map_data, aes(x = long, y = lat, group = group)) 
p1 <- p1 + geom_polygon(aes(fill = brk)) 
p1 <- p1 + geom_path(colour = 'black', linestyle = 2, size=0.25) 
# use a sequential color scale since that's appropriate for the data 
p1 <- p1 + scale_fill_brewer('Unemployment Rate (Jan 2011)', palette = 'YlGnBu') 
# use a proper projection for the U.S. 
p1 <- p1 + coord_map("albers", lat0=39, lat1=45) 
p1 <- p1 + geom_text(data = states, aes(x = x, y = y, label = state.abb, group = NULL), size = 2) 
p1 <- p1 + labs(x=NULL, y=NULL) 
p1 <- p1 + theme_map() 
p1 <- p1 + theme(legend.position="right") 
p1 

enter image description here

您還需要處理阿拉斯加&夏威夷。