How to integrate a map plot on a R shiny dashboards

378 views Asked by At

I'd like to integrate a map plot on my R shiny dashboard. The code for the map is this :

library(tidyverse)
library(ggplot2)
library(usmap)

load("hatecrime.RData")

df <- hatecrime %>% count(State) %>% rename(state = State)

plot_usmap(data = df, values = "n", color = "red") + 
  scale_fill_continuous(name = "Hatecrimes", label = scales::comma) + 
  theme(legend.position = "right")

In the body I want to use a tabPanel:

tabPanel("Map", plotOutput("usplot", height = 300))

But I don't know how to link the map to the server. Can someone help me out ?

1

There are 1 answers

0
langtang On

You can put your call to the plot_usmap directly within the renderPlot() call on the server-side, or you can have a function that returns the plot, and call that function from within the renderPlot

Example of the latter:

get_usmap = function(data = df, values = "n", color = "red") {
  plot_usmap(data = data, values = values, color = color) + 
    scale_fill_continuous(name = "Hatecrimes", label = scales::comma) + 
    theme(legend.position = "right")

On the server-side, you can call your plotting function from within renderPlot

output$usplot = renderPlot(get_usmap())