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.
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
In my code below (which works just fine) I would like all the fonts when I hover over country on world map to be either bold or non bold. What is happening is as per the following example - say I hover over USA then I get .
562,079 Deaths United States USA
Cases: 30,211,178
Population: 320,635,163
Deaths % by Population:v0.0097%
The "Deaths United Sates" is not bold.
Code
output$World_Map <- renderPlotly({
l <- list(color = toRGB("grey"), width = 0.5)
g <- list(
showframe = FALSE,
showcoastlines = FALSE,
projection = list(type = "kavrayskiy7")
)
fig <- plot_geo(worldmap)
fig <- fig %>% add_trace(
z = ~ worldmap$Deaths,
color = ~ worldmap$Deaths,
colors = 'Reds',
locations = ~ worldmap$Country_Alpha_Code,
marker = list(line = l),
hoverinfo = "text",
text = ~ glue::glue(
"Deaths: {Country.x} <b>{Country_Alpha_Code}<b>\nCases: {comma(Cases,digits=0)}<b>\nPopulation: {comma(Population,digits=0)}<b>\nDeaths % by Population: {comma(Deaths_Perc_Pop,digits=4)}%</b>"
),
hovertemplate = "%{z:,0f}<extra>%{text}</extra>"
)
fig <-
fig %>% colorbar(title = 'Deaths - Positive Cases Gradient', tickformat = ",0f")
fig <-
fig %>% layout(title = 'Covid19 Global Pandemic .... <br>Data Source:Johns Hopkins University of Medicine',
geo = g)
fig
})
Regards
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
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).