Search code examples
rshinyr-leaflet

How to Separate Lines for Labels?


I have the following code in R Shiny for a data dashboard I'm working on, but I want the "Median Carbon Level" to be on a seperate line than the "Percent Increase from 2015" variable when it shows up in the label.

library(shiny)
library(leaflet)

# Sample data
data <- data.frame(
  lat = c(9.145, 9.145),
  lng = c(40.4897, 40.4897),
  carbon_mean = c(2.34, 3.45),
  percent_increase = c(12.5, 20.3)
)

# Shiny app
ui <- fluidPage(
  leafletOutput("map")
)

server <- function(input, output, session) {
  output$map <- renderLeaflet({
    leaflet(data) %>%
      addTiles() %>%
      addMarkers(
        ~lng, ~lat,
        label = ~paste("Median Carbon Level:", round(carbon_mean, 2), "<br>",
                       "Percent Increase from 2015:", round(percent_increase, 2), "%")
      )
  })
}

shinyApp(ui, server)

I've tried adding a newline character, but I have not been able to seperate them into seperate lines in the label.


Solution

  • Wrap the text in HTML() to see the effect of <br> in the output. I also noticed that you have same lat and lng position for different values of carbon_mean and percent_increase so they both are shown at the same point.

    library(shiny)
    library(leaflet)
    
    # Sample data
    data <- data.frame(
      lat = c(9.145, 9.145),
      lng = c(40.4897, 40.4897),
      carbon_mean = c(2.34, 3.45),
      percent_increase = c(12.5, 20.3)
    )
    
    # Shiny app
    ui <- fluidPage(
      leafletOutput("map")
    )
    
    server <- function(input, output, session) {
      output$map <- renderLeaflet({
        leaflet(data) %>%
          addTiles() %>%
          addMarkers(
            ~lng, ~lat,
            label = ~HTML(paste("<br/>Median Carbon Level:", round(carbon_mean, 2),
               "<br/>Percent Increase from 2015:", round(percent_increase, 2), "%"))
          )
      })
    }
    
    shinyApp(ui, server)
    

    enter image description here