Libararies

# install.packages('rgdal')
# install.packages('plotly')
# install.packages('ggplot2')
# install.packages('devtools')
# Dev version

#suppressPackageStartupMessages(library(devtools))
#devtools::install_github('ropensci/plotly')

suppressPackageStartupMessages(library(rgdal))
suppressPackageStartupMessages(library(ggplot2))
suppressPackageStartupMessages(library(plotly))
packageVersion('plotly')
## [1] '4.7.1.9000'
packageVersion('ggplot2')
## [1] '2.2.1.9000'

Data

https://tools.wmflabs.org/kmlexport?article=List_of_state_and_territorial_capitols_in_the_United_States

File bookkeeping

readOGR could not open the file from the URL so down load it.

kmlURL <-'https://tools.wmflabs.org/kmlexport?article=List_of_state_and_territorial_capitols_in_the_United_States'
localkmlFile <- 'doc.kml'

if (!file.exists(localkmlFile)) {
    print(sprintf('%s file does not exist, downloading.',localkmlFile ))
    download.file(kmlURL, destfile = localkmlFile)
}

Data Pre Processing

spdf<-readOGR('doc.kml')
## OGR data source with driver: KML 
## Source: "C:\Users\reefe\Desktop\Csera\JH_Data\7. Data Products\cp2\doc.kml", layer: "Table of State Capitols"
## with 52 features
## It has 2 fields
df <- data.frame('longitude'=spdf@coords[,1], 
               'latitude'=spdf@coords[,2],
               'name'=spdf@data$Name)
df$clrcode <- round(abs(df$longitude)*df$latitude*-10)
df$hvr <- as.factor(paste( paste('LON',format(df$longitude,digits=6),sep=': '),
              paste('LAT',format(df$latitude,digits=6),sep=': '),
              df$name, sep='<br />'))

Plotly Plot State Capitols

from https://plot.ly/r/scatter-plots-on-maps/

Simple Scatter plot of the data. Fall back plot

{r echo=T, eval=F, fig.height=7, fig.width=10}

pal <- c("blue", "green", "orange", "red")
pal <- c("darkblue", "blue", "lightblue")
pal <- c("darkred", "red", "orange")


plot_ly(df, x=~longitude, y=~latitude,
        type='scatter', mode='markers',
        color=~longitude, colors=pal,
        text=~hvr, 
        hoverinfo='text') %>% 
    colorbar(title='Longitude' ) %>%
    layout( title='State Capitols<br />(Hover for info)')

Plot Geo

Parameters

g <- list(
  scope = 'usa',
  projection = list(type = 'albers usa'),
  showland = TRUE,
  showlakes = TRUE,
  landcolor = toRGB("gray95"),
  countrywidth = 1 ,
  subunitwidth = 1 ,  
  subunitcolor = toRGB("gray85"),
  countrycolor = toRGB("gray85") 
)

Plot Will render Map in Browser

plot_geo(df, lat = ~latitude, 
            lon = ~longitude, 
            locationmode = 'USA-states', 
            sizes=c(1,250), mode='markers') %>%
    add_markers(text= ~hvr) %>%  
    layout(
    title = 'State Capitols<br />(Hover for info)', geo = g) 

End