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.
Related
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
I posted this in the plotly community forum but got absolutely no activity! Hope you can help here:
I have map time-series data, some countries don’t have data and plotly does not plot them at all. I can have them outlined and they look different but it appears nowhere that the data is missing there (i.e. I want a legend entry). How can I achieve this? Here is a reprex:
library(plotly)
library(dplyr)
data = read.csv('https://github.com/lc5415/COVID19/raw/master/data.csv')
l <- list(color = toRGB("grey"), width = 0.5)
g <- list(
scope = 'world',
countrycolor = toRGB('grey'),
showframe = T,
showcoastlines = TRUE,
projection = list(type = 'natural earth')
)
map.time = data %>%
plot_geo() %>%
add_trace(z = ~Confirmed, color = ~Confirmed, frame = ~Date, colors = 'Blues',
text = ~Country, locations = ~Alpha.3.code, marker = list(line = l)) %>%
colorbar(title = 'Confirmed') %>%
layout(
title = 'Number of confirmed cases over time',
geo = g
) %>%
animation_opts(redraw = F) %>%
animation_slider(
currentvalue = list(
prefix = paste0("Days from ",
format(StartDate, "%B %dnd"),": "))) %>%
plotly_build()
map.time
Note that the countries with missing data (e.g. Russia) have as many data points as all other countries, the issue is not that they do not appear in the dtaframe passed to plotly.
The obvious way to handle this is to create a separate labels column for the tooltip that reads "No data" for NA values (with the actual value otherwise), then make your actual NA values 0. This will give a uniform appearance to all the countries but correctly tells you when a country has no data.
map.time = data %>%
mutate_if(is.numeric, function(x) {x[is.na(x)] <- -1; x}) %>%
plot_geo() %>%
add_trace(z = ~Confirmed, color = ~Confirmed, frame = ~Date, colors = 'Blues',
text = ~Country, locations = ~Alpha.3.code,
marker = list(line = l)) %>%
colorbar(title = 'Confirmed') %>%
layout(
title = 'Number of confirmed cases over time',
geo = g
) %>%
animation_opts(redraw = F) %>%
animation_slider(
currentvalue = list(
prefix = paste0("Days from ",
format(StartDate, "%B %dnd"),": "))) %>%
plotly_build()
Which gives:
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")
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)
I would like to combine two types of maps within one map in plotly, namely bubble and choropleth map. The objective is to show population size on a country level (choropleth) as well as on a city level (bubble) by hovering with the mouse over the map.
The plotly example code for a choropleth map is as follows:
library(plotly)
df <- read.csv('https://raw.githubusercontent.com/plotly/datasets/master/2014_world_gdp_with_codes.csv')
# light grey boundaries
l <- list(color = toRGB("grey"), width = 0.5)
# specify map projection/options
g <- list(
showframe = FALSE,
showcoastlines = FALSE,
projection = list(type = 'Mercator')
)
plot_ly(df, z = GDP..BILLIONS., text = COUNTRY, locations = CODE, type = 'choropleth',
color = GDP..BILLIONS., colors = 'Blues', marker = list(line = l),
colorbar = list(tickprefix = '$', title = 'GDP Billions US$'),
filename="r-docs/world-choropleth") %>%
layout(title = '2014 Global GDP<br>Source:CIA World Factbook',
geo = g)
The plotly example code for a bubble map is as follows:
library(plotly)
df <- read.csv('https://raw.githubusercontent.com/plotly/datasets/master/2014_us_cities.csv')
df$hover <- paste(df$name, "Population", df$pop/1e6, " million")
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")
)
plot_ly(df, lon = lon, lat = lat, text = hover,
marker = list(size = sqrt(pop/10000) + 1),
color = q, type = 'scattergeo', locationmode = 'USA-states',
filename="r-docs/bubble-map") %>%
layout(title = '2014 US city populations<br>(Click legend to toggle)', geo = g)
How could one possibly merge the two types of maps into one?
Great question! Here's a simple example. Note:
Use add_trace to add another chart type layer on top of the plot
the layout of the plot is shared across all traces. layout keys describe things like the map's scope, axes, title, etc. See more layout keys.
Simple bubble chart map
lon = c(-73.9865812, -118.2427266, -87.6244212, -95.3676974)
pop = c(8287238, 3826423, 2705627, 2129784)
df_cities = data.frame(cities, lat, lon, pop)
plot_ly(df_cities, lon=lon, lat=lat,
text=paste0(df_cities$cities,'<br>Population: ', df_cities$pop),
marker= list(size = sqrt(pop/10000) + 1), type="scattergeo",
filename="stackoverflow/simple-scattergeo") %>%
layout(geo = list(scope="usa"))
Interactive version
Simple choropleth chart
state_codes = c("NY", "CA", "IL", "TX")
pop = c(19746227.0, 38802500.0, 12880580.0, 26956958.0)
df_states = data.frame(state_codes, pop)
plot_ly(df_states, z=pop, locations=state_codes, text=paste0(df_states$state_codes, '<br>Population: ', df_states$pop),
type="choropleth", locationmode="USA-states", colors = 'Purples', filename="stackoverflow/simple-choropleth") %>%
layout(geo = list(scope="usa"))
Interactive version
Combined choropleth and bubble chart
plot_ly(df_cities, lon=lon, lat=lat,
text=paste0(df_cities$cities,'<br>Population: ', df_cities$pop),
marker= list(size = sqrt(pop/10000) + 1), type="scattergeo",
filename="stackoverflow/choropleth+scattergeo") %>%
add_trace(z=df_states$pop,
locations=df_states$state_codes,
text=paste0(df_states$state_codes, '<br>Population: ', df_states$pop),
type="choropleth",
colors = 'Purples',
locationmode="USA-states") %>%
layout(geo = list(scope="usa"))
Interactive version with hover text
Note that z and locations columns in the second trace are explicitly from the df_states dataframe. If they were from the same dataframe as the first trace (df_cities declared in plot_ly) then we could've just written z=state_codes instead of z=df_states$state_codes (as in the second example).