2016-07-16 7 views
0

Я пытаюсь создать карту с несколькими ресторанами в США по странам. Однако из-за большого диапазона значений бункеров все округа выглядят очень одинаково по цвету. Как я могу настроить количество ящиков, чтобы добавить больше цветов в диаграмму.Как настроить количество ящиков, используя библиотеку maptools в R

Я попытался очистить код, но может быть несколько лишних строк несвязанного кода ниже, которые я использую для других целей.

Вот код, который у меня есть.

##some libraries are not used 
library(rgeos) 
library(rgdal) 
library(maptools) 
library(readxl) 
library(tmap) 
library(gpclib) 

#reading data from excel file 
#source of the file http://www.ers.usda.gov/datafiles/Food_Environment_Atlas/Data_Access_and_Documentation_Downloads/Current_Version/DataDownload.xls . I am using local file in my computer 
data_restaurant <- read_excel(...) 
#reading shapes to drawn on the map chart 
# I am reading from local file but the actual source is http://www2.census.gov/geo/tiger/GENZ2010/gz_2010_us_050_00_20m.zip 
us_shape <- read_shape(..) 

#Removing Alaska, Hawaii and Puertorico 
us_shape <- us_shape[!(us_shape$STATE %in% c("02","15","72")),] 

#assign data to shape 
us_shape$FIPS <- paste0(us_shape$STATE, us_shape$COUNTY) 
us_shape <- append_data(us_shape, data, key.shp = "FIPS", key.data = "FIPS") 
restaurant_shape <- append_data(us_shape, data_restaurant, key.shp = "FIPS", key.data = "FIPS") 

#draw the map 
draw_map_adult_obs_2010 <- qtm(us_shape, fill = "PCT_OBESE_ADULTS10", fill.palette="Reds",title="2010 Adult Obesity by County, percent",title.position = c("center", "top")) 



##This didn't work because of gpclib library not working 
##US_states <- unionSpatialPolygons(us_shape, IDs=us_shape$STATE) 




#Draw chart restaurant 

tm_shape(restaurant_shape, projection="+init=epsg:2163") + 
    tm_polygons("FFR12", border.col = "grey30", title="", palette="Reds") + 
    tm_borders(lwd=2, col = "black", alpha = .5) + 
    tm_layout(title="2012 # of Restaurants by County in USA", 
      title.position = c("center", "top"), 
      legend.text.size=0.7) 

Вот что карта диаграмма выглядит как прямо сейчас. Как видно из легенд, всего 4 группы бинов. Как добавить дополнительные бункеры или создать собственный. Я потратил много часов, пытаясь найти решение для этого, не повезло.

Update #

я, наконец, смог найти решение, которое я искал. Это то, что я сделал

tm_shape(restaurant_shape,projection="+init=epsg:2163") + 
    tm_fill("FFR12", title = "", style = "fixed", 
      breaks = c(0, 50, 150, 250, 500,1000,1500, Inf), 
      palette = "Blues") + 
    tm_borders() + 
    tm_layout(title="2012 # of Restaurants by County in USA", 
      title.position = c("center", "top"), 
      legend.text.size=0.7) 

Мне нравится, как диаграммы выглядят на ggplot2, поэтому я могу попробовать и так.

Это то, что диаграмма выглядит сейчас: enter image description here

ответ

0

Поскольку вы используете сырые счетчики все равно (по сравнению с более надежным подходом, как нормализующих на 1К, жителей округа 10К или 100К) просто перейти к использованию логарифмической шкалы (вы можете сделать это с помощью тематических карт упак, но вот ggplot2 раствор):

library(albersusa) # devtools::install_github("hrbrmstr/albersusa") 
library(readxl) 
library(dplyr) 
library(maptools) 
library(rgeos) 
library(ggplot2) 
library(ggthemes) 
library(ggalt) 
library(viridis) 

URL <- "http://www.ers.usda.gov/datafiles/Food_Environment_Atlas/Data_Access_and_Documentation_Downloads/Current_Version/DataDownload.xls" 
fil <- basename(URL) 
if (!file.exists(fil)) download.file(URL, fil) 

restaurants <- read_excel(fil, 11) 

select(restaurants, FIPS, FFR12, FSR12) %>% 
    mutate(total=FFR12+FSR12) %>% 
    select(FIPS, total) -> restaurants 

counties <- counties_composite() 

us_map <- fortify(counties, region="fips") 

gg <- ggplot() 
gg <- gg + geom_map(data=us_map, map=us_map, 
        aes(long, lat, map_id=id), 
        color="#ffffff00", size=0.05, fill=NA) 
gg <- gg + geom_map(data=restaurants, map=us_map, 
        aes(fill=total, map_id=FIPS), 
        color="#ffffff", size=0.05) 
gg <- gg + scale_fill_viridis(name="Total:", trans="log10") 
gg <- gg + coord_proj(us_aeqd_proj) 
gg <- gg + theme_map() 
gg <- gg + theme(legend.position=c(0.8, 0.25)) 
gg 

enter image description here

но, пожалуйста рассмотреть вопрос нормализации данных каким-то образом.

+0

Ваша диаграмма выглядит намного лучше, чем моя, я мог бы попробовать использовать ggplot2. В любом случае, я смог достичь решения, которое я искал выше. Вот что я сделал tm_shape (restaurant_shape, проекция = "+ INIT = EPSG: 2163") + tm_fill ("FFR12", название = "ВВП", стиль = "фиксированный", брейки = с (0, 50 , 150, 250, 500,1000,1500, Inf), palette = "Blues") + tm_borders() + tm_layout (title = "2012 # of Restaurants by County in USA", title.position = c («center», «top»), legend.text.size = 0.7) – dgl