Plotly map hovers don't render in R - 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')

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

Add horizontal scroll bar in plotly chart

How can I add a horizontal x-axis scroll bar in a long plotly line chart?
library(plotly)
x <- c(1:100)
random_y <- rnorm(100, mean = 0)
data <- data.frame(x, random_y)
fig <- plot_ly(data, x = ~x, y = ~random_y, type = 'scatter', mode = 'lines')
fig
Case that rangeslider() does not work.
VaccinationWeek<-c("2020w1","2020w1","2020w1","2020w2","2020w2","2020w2")
Country<-c("EU","CHE","ITA","EU","CHE","ITA")
Value<-c(3,2,1,5,3,2)
dat<-data.frame(VaccinationWeek,Country,Value)
plot_ly(dat,
x = ~VaccinationWeek,
y = ~Value/100,
text = ~Value,
color = ~Country,
customdata = dat$Country) %>%
add_trace(
type = 'scatter',
mode = 'lines+markers',
hovertemplate = paste("Country: %{customdata}",
"Uptake full vaccination (%): %{y}",
"<extra></extra>",
sep = "\n"),
hoveron = 'points') %>%
add_text(
textposition = "top center",
showlegend = F,
hoverinfo = "skip") %>%
layout(font = list(color = '#a2a2a2'),title=list(text="by reporting week",x = 0),
xaxis = list(fixedrange = TRUE,title="",showgrid = FALSE,tickangle = 45
),
yaxis = list(fixedrange = TRUE,rangeslider = list(),title="",showgrid = FALSE,showline=T,tickformat = "%"),
hovermode = "x unified",
hoverlabel = "none",
legend = list(itemclick = F, itemdoubleclick = F))%>%
config(modeBarButtonsToRemove = c('toImage',"zoom2d","toggleSpikelines","hoverClosestCartesian","hoverCompareCartesian","drawline","autoScale2d" ,"resetScale2d","zoomIn2d","zoomOut2d","pan2d",'select2d','lasso2d'))%>%
config(displaylogo = FALSE)
I'd suggest using a rangeslider:
library(plotly)
x <- c(1:100)
random_y <- rnorm(100, mean = 0)
data <- data.frame(x, random_y)
fig <- plot_ly(data, x = ~x, y = ~random_y, type = 'scatter', mode = 'lines') %>%
layout(xaxis = list(rangeslider = list()))
fig
After #firmo23's edit:
library(plotly)
VaccinationWeek <- c("2020w1", "2020w1", "2020w1", "2020w2", "2020w2", "2020w2")
Country <- c("EU", "CHE", "ITA", "EU", "CHE", "ITA")
Value <- c(3, 2, 1, 5, 3, 2)
dat <- data.frame(VaccinationWeek, Country, Value)
plot_ly(
dat, x = ~ VaccinationWeek, y = ~ Value / 100, text = ~ Value, color = ~ Country, customdata = dat$Country
) %>%
add_trace(
type = 'scatter', mode = 'lines+markers', hovertemplate = paste(
"Country: %{customdata}", "Uptake full vaccination (%): %{y}", "<extra></extra>", sep = "\n"
), hoveron = 'points'
) %>%
add_text(textposition = "top center", showlegend = F, hoverinfo = "skip") %>%
layout(
font = list(color = '#a2a2a2'), title = list(text = "by reporting week", x = 0), xaxis = list(
fixedrange = TRUE, title = "", showgrid = FALSE, tickangle = 45, rangeslider = list()
), yaxis = list(
fixedrange = TRUE, rangeslider = list(), title = "", showgrid = FALSE, showline = T, tickformat = "%"
), hovermode = "x unified", hoverlabel = "none", legend = list(itemclick = F, itemdoubleclick = F)
) %>%
config(
modeBarButtonsToRemove = c(
'toImage',
"zoom2d",
"toggleSpikelines",
"hoverClosestCartesian",
"hoverCompareCartesian",
"drawline",
"autoScale2d" ,
"resetScale2d",
"zoomIn2d",
"zoomOut2d",
"pan2d",
'select2d',
'lasso2d'
),
displaylogo = FALSE
)

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

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")

R Plotly Choropleth Hover Text Number

Using this code:
library(plotly)
df <- read.csv("https://raw.githubusercontent.com/plotly/datasets/master/2011_us_ag_exports.csv")
df$hover <- with(df, paste(state, '<br>', "Beef", beef, "Dairy", dairy, "<br>",
"Fruits", total.fruits, "Veggies", total.veggies,
"<br>", "Wheat", wheat, "Corn", corn))
# give state boundaries a white border
l <- list(color = toRGB("white"), width = 2)
# specify some map projection/options
g <- list(
scope = 'usa',
projection = list(type = 'albers usa'),
showlakes = TRUE,
lakecolor = toRGB('white')
)
plot_ly(df, z = total.exports, text = hover, locations = code, type = 'choropleth',
locationmode = 'USA-states', color = total.exports, colors = 'Purples',
marker = list(line = l), colorbar = list(title = "Millions USD")) %>%
layout(title = '2011 US Agriculture Exports by State<br>(Hover for breakdown)', geo = g)
Is there a way to remove the seemingly-random number that appears before the value of df$hover when hovering?
Your help is greatly appreciated.

Resources