In this article, we are going to see how to visualize the hexabin plot in R Programming Language.
Hexabin map employs hexagons to divide the area into multiple sections and assign each one a color. The graphic region (which could be a geographical location) is divided into a slew of hexagons, with the number of data points in each being counted and shown by a color gradient.
This diagram is used to show density, with the hexagonal shape allowing for the easy creation of contiguous areas while separating the space into discrete pieces.
Download the data using this link. This data stores the polygon data of the US States
Basic Hexabin Map
To plot hexabin with the us_states_hexgrid dataset for this we will create dataframe from this dataset and then we will plot spatial data.
# R library library (tidyverse) # handle the data
library (geojsonio) # handle the geojson data
library (RColorBrewer) # for color palette
library (rgdal) # handling the spatial data
# load the geospatial data us_data <- geojson_read ( "us_states_hexgrid.geojson" , what = "sp" )
# polygon spatial data us_data@data = us_data@data %>% mutate (google_name = gsub ( " \\(United States\\)" , "" , google_name))
# plot the basic Hexabin Map plot (us_data)
|
Output:
Merging the data with the Choropleth Map
Hexabin is used to plot to scatter plots with high-density data and here we will merge the data with the spatial features from geojson file and then plot hexabin using ggplot.
# R library library (tidyverse) # handle the data
library (geojsonio) # handle the geojson data
library (RColorBrewer) # for color palette
library (rgdal) # handling the spatial data
# load the geospatial data us_data <- geojson_read ( "us_states_hexgrid.geojson" ,
what = "sp" )
# polygon spatial data us_data@data = us_data@data %>% mutate (google_name = gsub ( " \\(United States\\)" ,
"" , google_name))
# library to convert data to a tidy data library (broom)
us_data@data = us_data@data %>% mutate (
google_name = gsub ( " \\(United States\\)" ,
"" , google_name))
us_data_fortified <- tidy (us_data,
region = "google_name" )
# getting the US state Marriage data /holtzy/R-graph-gallery/master/DATA/State_mariage_rate.csv", sep = "," , na.strings= "---" , header = T)
# extracting the data sequence data %>% # getting the data for year 2015
ggplot ( aes (x = y_2015)) +
# preparing the histogram
geom_histogram (bins = 10, fill= '#69b3a2' , color= 'white' )
# merging the data with the spatial features from geojson file us_data_fortified <- us_data_fortified %>% left_join (. , data, by= c ( "id" = "state" ))
# preparing a choropleth map ggplot () +
geom_polygon (data = us_data_fortified, aes (
fill = y_2015, x = long, y = lat, group = group)) +
scale_fill_gradient (trans = "log" ) +
coord_map ()
|
Output: