R - plotly - combine bubble and chorpleth map

余生颓废 提交于 2019-12-03 21:49:57

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!