Color USA map based on a Categorical variable using Plotly in R

Hello friends! we’ll be learning to create the Color USA map based on a Categorical variable using Plotly in R. Very simple and reusable code in tutorial.

Data

StateSales
ALHigh
AKMedium
AZMedium
ARMedium
CAVery Low
COVery High
CTLow
DEMedium
FLVery High

Code

Following reusable code can be applied to any other dataset.

Load library

library(dplyr)
library(plotly)
library(htmlwidgets)
library(RColorBrewer)

Load data

df <- read.csv("states.csv")

Factoring

df$Sales = factor(df$Sales)
df$val = as.numeric(df$Sales)
nfactor = length(levels(df$Sales))
colr <- brewer.pal(n = nfactor,name = "Set1")
levels(df$Sales) <- c("Very Low" , "Low", "Medium", "High", "Very High")
names(colr) = levels(df$Sales)
colrS = function(n){
CUTS = seq(0,1,length.out=n+1)
rep(CUTS,ifelse(CUTS %in% 0:1,1,2))
}

Creating color data frame

colorScale <- data.frame(z=colrS(nfactor),
col=rep(colr,each=2),stringsAsFactors=FALSE)

Plotting Map

p <- plot_ly( data = df, type = "choropleth", locations = ~ State, locationmode = "USA-states", z = df$val, colorscale= colorScale, # or "Greens", colorbar=list(tickvals=1:nfactor, ticktext=names(colr)) ) %>%
layout(geo = list(scope = "usa")) %>%
colorbar(title = "Color Scales")
p

USA map colored based on categorical column

Saving Map as html file

saveWidget(p, 'USA Map.html')

Get the code here

Keep visiting Analytics Tuts for more tutorials.

Thanks for reading! Comment your suggestions and queries


One comment

Leave a Reply

Your email address will not be published. Required fields are marked *