Plotly Map New York City Using R - r

Plotly creates nice maps where the scope term defines the area. I'm wondering if I can make the map so it only shows New York City?
I've read the documentation on scope (https://plotly.com/python/reference/#layout-geo-scope), and see it does not involve any cities, so maybe someone else has a way to solve this?
library(plotly)
df <- read.csv('https://raw.githubusercontent.com/plotly/datasets/master/2011_february_us_airport_traffic.csv')
# geo styling
g <- list(
scope = 'usa',
projection = list(type = 'albers usa'),
showland = TRUE,
landcolor = toRGB("gray95"),
subunitcolor = toRGB("gray85"),
countrycolor = toRGB("gray85"),
countrywidth = 0.5,
subunitwidth = 0.5
)
fig <- plot_geo(df, lat = ~lat, lon = ~long)
fig <- fig %>% add_markers(
text = ~paste(airport, city, state, paste("Arrivals:", cnt), sep = "<br />"),
color = ~cnt, symbol = I("square"), size = I(8), hoverinfo = "text"
)
fig <- fig %>% colorbar(title = "Incoming flights<br />February 2011")
fig <- fig %>% layout(
title = 'Most trafficked US airports<br />(Hover for airport)', geo = g
)
fig

Related

full usa map in R

I am trying to plot the dataset nycflight 2013. However I can't show the full usa map in r. Airports that are located in Hawaii and Alaska are not showing.
this is my code:
library(tidyverse)
library(plotly)
#reading
flight<-read.csv('flight.csv')
airports<-read.csv('airports.csv')
flighsort<-flight[order(flight$airline),]
#airports locations
airports<-read.csv('airports.csv')
#clearning data for map
#converting lon_Dest_airport from factor to character to map it
AirportsMap <- flight %>%
mutate(lon_Dest_airport = parse_number(as.character(lon_Dest_airport)))
#cleaning the original file to get the number of flights between each two airports
AirportsMap<-AirportsMap %>% group_by(origin_airport,dest_airport,lon_origin_airport,lat_origin_airport,
lon_Dest_airport,lat_Dest_airport) %>% tally()
#drawing the map
geo <- list(
scope = 'usa',
projection = list(type = 'world'),
showland = TRUE,
landcolor = toRGB("gray95"),
countrycolor = toRGB("gray80")
)
#adding marker for the three origin airports
plot_geo(locationmode = 'USA-states') %>%
add_markers(
data=airports, x = ~lon, y = ~lat, text=~airport,size = 0.1,
hoverinfo = "text",alpha = 0.5) %>%
#adding flights routes
add_segments(
data = AirportsMap,
x = ~lon_origin_airport, xend = ~lon_Dest_airport,
y = ~lat_origin_airport, yend = ~lat_Dest_airport,
alpha = 0.3
) %>%
#adding a title
layout(
title = 'NYC Flights 2013<br>(Hover for airport names)',
geo = geo, showlegend = FALSE
)
any help is appreciated. thanks

Hover text for plot_geo function in plotly

I want to display the county name(subregion) and the population value(pop_cat) in hover.
Here's what i tried,
library(tidyverse)
library(plotly)
df <- read.csv("https://raw.githubusercontent.com/bcdunbar/datasets/master/californiaPopulation.csv")
cali <- map_data("county") %>%
filter(region == 'california')
pop <- df %>%
group_by(County.Name) %>%
summarise(Pop = sum(Population))
pop$County.Name <- tolower(pop$County.Name) # matching string
cali_pop <- merge(cali, pop, by.x = "subregion", by.y = "County.Name")
cali_pop$pop_cat <- cut(cali_pop$Pop, breaks = c(seq(0, 11000000, by = 500000)), labels=1:22)
geo <- list(
scope = 'usa',
showland = TRUE,
landcolor = toRGB("gray95"),
countrycolor = toRGB("gray80")
)
library(plotly)
geo <- list(
scope = 'usa',
showland = TRUE,
landcolor = toRGB("gray95"),
countrycolor = toRGB("gray80")
)
p <- cali_pop %>%
group_by(group) %>%
plot_geo(
x = ~long, y = ~lat, color = ~pop_cat, colors = c('#ffeda0','#f03b20'),
text = ~pop_cat, hoverinfo = 'text') %>%
add_polygons(line = list(width = 0.4)) %>%
add_polygons(
fillcolor = 'transparent',
line = list(color = 'black', width = 0.5),
showlegend = FALSE, hoverinfo = 'none'
) %>%
layout(
title = "California Population by County",
geo = geo)
p
Although I gave text = ~pop_cat, hoverinfo = 'text' in plot_geo function, it's not getting displayed when i hover on the plot. What should i do to display both pop_cat and subregion when i hover over the plot.
This is the plot that got generated. I have zoomed in the California region.
There is some kind of bug in plotly. As said by #MLavoie you can find the solution here https://github.com/ropensci/plotly/issues/1152
I tried with the dev version of plotly and it's fixed. Also to display the county name and population i used text = ~paste(cali_pop$subregion, "<br />", cali_pop$pop_cat)
If you are still struggling with getting a hover even after installing from developer version, and if the error says something like Error: package or namespace load failed for ‘plotly’ in get(Info[i, 1], envir = env): lazy-load database, just refresh R-session, that worked for me.
#Harikrishnan for your answer. It helped me.

Plotly hoverinfo wont work in R

So I copied the example off of plotly for R on making a bubble map. I can currently make a bubble map but I am unable to make hoverinfo work. I have seen on other posts that hoverinfo has given other people problems but none of the fixes I have found is making mine work. I have given a small amount of the data that I am using below.
Can anybody who knows plotly see if I am making a small mistake that I am not seeing?
Data
All_Time_Backers_city <- c(871,25,478,25,14,193)
Latitude <- c(32.44861,42.10472,42.48500,34.06583,34.77444,41.93167)
Longitude <- c(-99.73278,-70.94583,-71.43333,-84.67694,-96.67806,-87.98889)
City <- c("Abilene","Abington","Acton","Acworth","Ada","Addison")
z <- data.frame(All_Time_Backers_city, Latitude, Longitude, City)
Code
library(plotly)
z$q <- with(z, cut(All_Time_Backers_city, quantile(All_Time_Backers_city)))
levels(z$q) <- paste(c("1st", "2nd", "3rd", "4th", "5th"), "Quantile")
z$q <- as.ordered(z$q)
g <- list(
scope = 'usa',
projection = list(type = 'albers usa'),
showland = TRUE,
landcolor = toRGB("gray85"),
subunitwidth = 1,
countrywidth = 1,
subunitcolor = toRGB("white"),
countrycolor = toRGB("white")
)
p <- plot_geo(z, locationmode = 'USA-states', sizes = c(5, 250)) %>%
add_markers(
x = ~Longitude, y = ~Latitude, size = ~All_Time_Backers_city, color =
~q,
text = ~paste(City, "<br />", All_Time_Backers_city, "Backers"),
hoverinfo = "text+x+y"
)%>%
layout(title = 'Backers City All Time', geo = g)
p
I found out what the problem with getting the boxes to pop up. I had a few data points that were in Canada and a few in mexico. The map i was using for plotly was a US map only, i still had points plotting outside the map but the boxes did not pop up when the mouse hovered over. I had to change to a north america sized map.
Code:
z$q <- with(z, cut(All_Time_Backers_city, quantile(All_Time_Backers_city)))
levels(z$q) <- paste(c("1st", "2nd", "3rd", "4th", "5th"), "Quantile")
z$q <- as.ordered(z$q)
g <- list(
scope = 'north america',
showland = TRUE,
landcolor = toRGB("grey83"),
subunitcolor = toRGB("white"),
countrycolor = toRGB("white"),
showlakes = TRUE,
lakecolor = toRGB("white"),
showsubunits = TRUE,
showcountries = TRUE,
resolution = 50,
projection = list(
type = 'conic conformal',
rotation = list(lon = -100)
),
lonaxis = list(
showgrid = TRUE,
gridwidth = 0.5,
range = c(-140, -55),
dtick = 5
),
lataxis = list(
showgrid = TRUE,
gridwidth = 0.5,
range = c(15, 70),
dtick = 5
)
)
p <- plot_geo(z, sizes = c(5, 250))%>%
add_markers(x = ~Longitude, y = ~Latitude,
size = ~All_Time_Backers_city,
color = ~q, text = ~paste(z$City, "<br />", z$All_Time_Backers_city,
"Backers")
)%>%
add_trace(
z = ~Mapping$`Mean Campaign USD`, text = ~Mapping$hover, locations =
~Mapping$code
,locationmode="USA-states")%>%
layout(title = 'Backers City All Time', geo = g)
p

plotly map not rendering in r viewer or 'view in new window'

Having issues with plotly. Fairly new to plotly. My issue: script below (template taken directly from plotly's site) does not render plotly scatter in R studio viewer. I've tried opening in a new window as described here: Plotly Maps Not Rendering in R
The code below was working previously (i.e. renders in the 'view new window'). Tried to use it yesterday and this morning; all I get is the title and colorbar.
library(plotly)
p2c_Map_Data$text <- with(p2c_Map_Data,
paste(State, City, Zip, SalesCount, CustomerProspect,RevenuesProspect,
'<br>', "Days to Convert", MedianConversionTimeDays,'<br>',
"Touchpoint Count", MedianPathLength, "<br>",
"Sales", Revenues))
#give state boundaries a border
l <- list(color = toRGB("white"), width = 2)
# specify some map projection/options
g <- list(
scope = 'usa',
projection = list(type = 'albers usa'),
showland = TRUE,
landcolor = toRGB("gray95"),
subunitcolor = toRGB("gray85"),
countrycolor = toRGB("gray85"),
countrywidth = 0.5,
subunitwidth = 0.5
)
p <- plot_geo(p2c_Map_Data, lat = ~latitude, lon = ~longitude) %>%
add_markers(
text = ~paste(p2c_Map_Data$State, p2c_Map_Data$City, p2c_Map_Data$Zip,
paste("Sales Count:", p2c_Map_Data$SalesCount),
paste("CustomerProspect:", p2c_Map_Data$CustomerProspect),
paste("Revenues:", p2c_Map_Data$Revenues),
paste("RevenuesProspect:", p2c_Map_Data$RevenuesProspect),
paste("Days to Convert:", p2c_Map_Data$MedianConversionTimeDays),
paste("Touchpoint Count:", p2c_Map_Data$MedianPathLength), sep = "<br>"),
color = ~p2c_Map_Data$Revenues, symbol = I("square"), size = I(10), hoverinfo = "text") %>%
colorbar(title = "Revenues") %>%
layout(title = 'Map Data Report<br />FY 16', geo = g)

Render blank plot using plot_geo() in ShinyApp R

I am doing my final project for data visualization.
I would like to render a map with markers on it using Plotly in ShinyApp. The function I am using is plot_geo(). However, the plot works perfectly in the normal R environment, but it fails to render in ShinyApp, only displaying the blank plot. And also no error message is reported.
I have been stuck here for long. Can anyone help? Thanks!
My code (ShinyApp)
library(shiny)
library(plotly)
library(RColorBrewer)
library(ggplot2)
# Define UI for application
ui <- fluidPage(
# Application title
titlePanel("Times University Ranking"),
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
selectInput("year",
"Select a year",
c(2011:2016))
),
# Show a plot of the generated distribution
mainPanel(
plotOutput("map")
)
)
)
# Define server logic required to draw a histogram
server <- function(input, output) {
times <- data.frame(read.csv("./times.csv", header = TRUE))
d <- reactive({
a <- subset(times, year == input$year)
return (a)
})
g <- list(
scope = 'world',
projection = list(type = 'Mercator'),
showframe = FALSE,
showland = TRUE,
showsubunits = TRUE,
landcolor = toRGB("gray95"),
subunitcolor = toRGB("gray85"),
countrycolor = toRGB("gray65"),
countrywidth = 0.5,
subunitwidth = 0.5
)
output$map <- renderPlotly({
p <- plot_geo(data = d(), lat = ~lat, lon = ~lon,
color = ~as.numeric(rescale),
mode = 'markers', colors = "Spectral") %>%
add_markers(text = ~paste(paste("Rank:", world_rank),
university_name, country,
year, sep = "<br />"),
hoverinfo = "text") %>%
colorbar(title = "World Rank") %>%
layout(title = paste(input$year, "Times University Ranking on the Map"),
geo = g)
})
}
# Run the application
shinyApp(ui = ui, server = server)
Normal R code
library(plotly)
library(RColorBrewer)
input <- read.csv("times.csv", header = TRUE)
df <- data.frame(subset(input, year == 2015))
df <- df[sort.int(df$No, decreasing = TRUE), ]
# geo styling
g <- list(
scope = 'world',
projection = list(type = 'Mercator'),
showframe = FALSE,
showland = TRUE,
showsubunits = TRUE,
landcolor = toRGB("gray95"),
subunitcolor = toRGB("gray85"),
countrycolor = toRGB("gray65"),
countrywidth = 0.5,
subunitwidth = 0.5
)
p <- plot_geo(data = df, lat = ~lat,
lon = ~lon, color = ~as.numeric(rescale), mode = 'markers',
colors = "Spectral") %>%
add_markers(
text = ~paste(paste("Rank:", world_rank), university_name,
country, year, sep = "<br />"),
hoverinfo = "text") %>%
colorbar(title = "World Rank") %>%
layout(title = '2016 Times University Rankings on the map', geo = g)

Resources