Plotly hoverinfo wont work in R - 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

Related

Plotly Map New York City Using 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

How to make user defined / explicit colorscale and legend in plotly?

I have a dataset subsetted by month. However, when I graph each subset, the colorscale and range of legend are all different. How can I explicitly define this, so that it's consistent across all subsets?
So in the example below, I'd like the colorscale and range of legend to be the same for the unfiltered dataset and the filtered one.
github link to dataset
#original dataset. I want to construct the legend with this
weather <- read.csv("weather2_rmse.csv") %>%
mutate(date_of_forecast = as.Date(date_of_forecast))
#filtered. I want to construct the points with this
data <- filter(weather, date_of_forecast == "2015-02-01")
weather_map <- function(data) {
# change default color scale title
m <- list(colorbar = list(title = ""))
# geo styling
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(20, 60),
dtick = 5
)
)
#the plotly part
p <- plot_geo(data, lat = ~latitude, lon = ~longitude, color = ~rmse) %>%
add_markers(
text = ~paste(data$rmse, "RMSE"), hoverinfo = "text"
) %>%
layout(title = 'Average RMSE of MaxTemp Forecasts by Month<br>xxxxxxxxxx', geo = g)
p
}
For example this way: Define a scale, e.g.
scl = list(c(0, "rgb(0, 0, 255)"), list(1, "rgb(0, 255, 0)"))
(You can also add more values, this is based on quantiles AFAIK. So setting it like this
scl = list(c(0, "rgb(0, 0, 255)"), list(0.1, "rgb(0, 0, 255)"),
c(0.1, "rgb(0, 255, 0)"), list(1, "rgb(0, 255, 0)"))
Will make the first 10% of your values be blue, the remainder green.
Then, modify your plot call e.g. like this:
p <- plot_geo(data) %>%
add_markers(y = ~latitude, x = ~longitude,
mode = "markers", type = "scatter",
marker = list(color = ~rmse,
colorscale = scl,
cauto = FALSE,
colorbar = list(title=""),
cmax = 15,
cmin = 0)) %>%
layout(title = 'Average RMSE of MaxTemp Forecasts by Month<br>xxxxxxxxxx', geo = g)
p
By setting the exact limits with cmax and cmin you should have the same scale across subplots

Plotly map hovers don't render in R

Using the example code from Plotly, the map hovers don't render in RStudio (or a compiled .html file using RMarkdown):
library(plotly) # version ‘4.7.1’
df <- read.csv('https://raw.githubusercontent.com/plotly/datasets/master/2014_us_cities.csv')
df$q <- with(df, cut(pop, quantile(pop)))
levels(df$q) <- paste(c("1st", "2nd", "3rd", "4th", "5th"), "Quantile")
df$q <- as.ordered(df$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(df, locationmode = 'USA-states', sizes = c(1, 250)) %>%
add_markers(
x = ~lon, y = ~lat, size = ~pop, color = ~q, hoverinfo = "text",
text = ~paste(df$name, "<br />", df$pop/1e6, " million")
) %>%
layout(title = '2014 US city populations<br>(Click legend to toggle)', geo = g)
p
I've also tried hovertext instead of text without any success.
I think it is due to a newer version of plot_ly that you are using (hoverinfo = "text" is no longer needed) :
Try this:
library(plotly) # version ‘4.7.1’
df <- read.csv('https://raw.githubusercontent.com/plotly/datasets/master/2014_us_cities.csv')
df$q <- with(df, cut(pop, quantile(pop)))
levels(df$q) <- paste(c("1st", "2nd", "3rd", "4th", "5th"), "Quantile")
df$q <- as.ordered(df$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(df, locationmode = 'USA-states', sizes = c(1, 250)) %>%
layout(title = '2014 US city populations<br>(Click legend to toggle)', geo = g) %>%
add_markers(x = ~lon, y = ~lat, size = ~pop, color = ~q, text = ~paste(df$name, "<br />", df$pop/1e6, " million")
)
p
It works on my RStudio.
This was recently fixed in the dev version devtools::install_github('ropensci/plotly')

Cannot display Plotly graph on Github pages

I have a plotly based graph in R and I wish to display it on my github pages. I am not able to display the graph when I convert into to markdown. I was able to render an html of plotly plot, but I dont know how to use with pages.Here is my rep and file for the below markdown
library(XML)
library(ggplot2)
library(tidyr)
library(dplyr)
library('maps')
library('ggthemes')
library('plotly')
A_loc<-tbl_df(readLines("https://raw.githubusercontent.com/jpatokal/openflights/master/data/airports.dat"))
New_A_loc<-as.data.frame(sapply(A_loc, function(x) gsub("\"", "", x)))
New_A_loc<-separate(data = New_A_loc, col = value, into = c("Airport_id", "Name","City","Country","IATA","ICAO","Lat","Long","Alt","Timezone","DST","TZ","Type","Source"), sep = ",")
New_A_loc$Lat <- as.numeric(New_A_loc$Lat)
New_A_loc$Long <- as.numeric(New_A_loc$Long)
New_A_loc$Alt<-as.numeric(New_A_loc$Alt)
New_A_loc$Name<-as.character(New_A_loc$Name)
g <- list(showframe = FALSE,
coastlinecolor = toRGB("white"),
showland = TRUE,
landcolor = toRGB("gray80"),
showcountries = TRUE,
countrycolor = toRGB("white"),
countrywidth = 0.2,
projection = list(type = 'Mercator'))
plot_geo(New_A_loc,
lat = ~Lat,
lon = ~Long,
text = ~City,
mode='markers',
marker = list(color = toRGB("purple"),
opacity = 0.5,
line = list(color = toRGB("purple"),
width = 0.5))
) %>%
layout(geo = g) %>% htmlwidgets::saveWidget("New_2.html")

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)

Resources