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).
Related
When hovering over a country the numbers are shown as say 125.115k - I want to show it as 125,115
I tried using library(formattable) and something along the lines of z = comma(worldmap$Deaths,digits = 1)
My code is below
output$World_Map <- renderPlotly({
g <- list(
showframe = FALSE,
showcoastlines = FALSE,
projection = list(type = 'Mercator')
)
plot_ly(
worldmap,
type = 'choropleth',
locations = worldmap$COUNTRY_ALPHA_3_CODE,
z = worldmap$Deaths,
text = paste("Number of Deaths: ",worldmap$COUNTRY_SHORT_NAME,"\n",comma(worldmap$Cases, digits = 0),"\n","Number of Cases: ",worldmap$COUNTRY_SHORT_NAME),
colorscale = "Reds"
) %>% layout(title = "<b>Covid19 Global Pandemic .... Data Source: <a href='https://coronavirus.jhu.edu/'>Johns Hopkins University of Medicine</a><b>", geo = g)
})
For comma rendering numbers, I use prettyNum from base R, also comma function is available in scales package.
number_a <- 123456
prettyNum(number_a, big.mark = ",")
[1] "123,456"
Your question is about text tooltip in Plotly. You can do something like this, with hoverinfo/hovertemplate and text parameters.
Of course there are other manners to do it.
Because I don't have your data, I use an example from plotly website.
library(plotly)
# code for example
# https://plotly.com/r/choropleth-maps/#using-builtin-country-and-state-geometries
# doc for hovertemplate
# https://plotly-r.com/controlling-tooltips.html#tooltip-text
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')
)
fig <- plot_geo(df)
fig <- fig %>% add_trace(
z = ~GDP..BILLIONS., color = ~GDP..BILLIONS., colors = 'Blues',
locations = ~CODE, marker = list(line = l),
hoverinfo = "text",
text = ~glue::glue("{COUNTRY} <b>{CODE}</b>"),
hovertemplate = "%{z:,0f}<extra>%{text}</extra>"
)
fig <- fig %>% colorbar(title = 'GDP Billions US$', tickformat = ",0f")
fig <- fig %>% layout(
title = '2014 Global GDP<br>Source:CIA World Factbook',
geo = g
)
fig
With this you can easily configure your hover info / tooltip.
See here for more examples :
https://plotly.com/r/choropleth-maps/#customize-choropleth-chart
For French number (space instead of comma), you can at the end config locale:
fig %>%
config(locale = 'fr')
Using these instructions: win.graph()
map("usa")
map("usa",col='white',fill=T, xlim=c(-73.7 ,-71.52), ylim=c(38.6,40.92))
points.geodata(x=dat_zero,coords=dat_zero$coords,dat_zero$data,pt.divide="quintiles",
col=1:5,xlim=c(-73.7 ,-71.52), ylim=c(38.6,40.92),add.to.plot = T)
not from mistakes but does not do it.
welcome to SO. Generally it's a good idea to include what packages you may have loaded and more description of the problem itself.
Here's an approach using plotly. I'm using ggplot2::map_data() to generate some sample data (larger dataset) and show how it works:
library(ggplot2)
library(plotly)
dat <- map_data(map = 'county')
# map_data() is a large dataset, I'm limiting the map to 50 observations
# the coords$value field is the variable that determines the color of the mapped point
coords <- dat[sample(sample(x = 1:nrow(dat), size = 50, replace = T)), ]
coords$value <- rnorm(n = nrow(coords), mean = 10, sd = 3)
# some code to let plotly know we're plotting a map (projection etc.)
g <- list(
scope = 'usa',
projection = list(type = 'Mercator'),
showland = TRUE,
landcolor = toRGB("gray85"),
subunitwidth = 1,
countrywidth = 1,
subunitcolor = toRGB("white"),
countrycolor = toRGB("white")
)
plt <- plot_geo(locationmode = 'USA-states', sizes = c(1, 250), data = coords) %>%
add_markers(x = ~long, y = ~lat, color = ~value) %>%
layout(title = 'County Map',
geo = g)
OUTPUT
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
I am trying to change the color of the polygons drawn using leaflet and Mapzen. The colors are clearly visible with the current tiles but not as much with others, such as the addTiles(). How should I change the argument for the three polygons?
For the code to work you must enter a mapzen key.
library(rmapzen)
library(leaflet)
Sys.setenv(MAPZEN_KEY = "mapzen-******")
#https://tarakc02.github.io/rmapzen/#introduction
ucb <- mz_geocode("Via Giovanni Spadolini 7, Milan, Italy")
isos <- mz_isochrone(
ucb,
costing_model = mz_costing$auto(),
contours = mz_contours(c(5, 10, 15)),
polygons = TRUE
)
leaflet(as_sp(isos)) %>%
addProviderTiles("CartoDB.DarkMatter") %>%
addPolygons(color = ~color, weight = 1) %>%
addLegend(colors = ~color,
labels = ~paste(contour, "minutes"),
title = "Drive times from <br/> Centro Leoni")
I realized that the polygons should be added separately and instead of:
leaflet(as_sp(isos))
Solution:
iso10 <- as_sp(mz_isochrone(
ucb,
costing_model = mz_costing$auto(),
contours = mz_contours(10),
polygons = TRUE
))
iso30 <- as_sp(mz_isochrone(
ucb,
costing_model = mz_costing$auto(),
contours = mz_contours(30),
polygons = TRUE
))
iso60 <- as_sp(mz_isochrone(
ucb,
costing_model = mz_costing$auto(),
contours = mz_contours(60),
polygons = TRUE
))
m = leaflet() %>%
addProviderTiles("CartoDB.DarkMatter") %>%
addPolygons(data = iso10, color = "red", fillColor = "red")%>%
addPolygons(data = iso30, color = "green", fillColor = "green")%>%
addPolygons(data = iso60, color = "blue", fillColor = "blue")
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)