Search code examples
rggplot2shinylatexmathjax

R: How to use mathematical notation in ggplot labels within a shiny app?


I am trying to use mathematical notation/symbols in the labels of a ggplot2 figure within a shiny app.

The minimal example below uses shiny's built-in support for MathJax to include mathematical notation with TeX-style syntax in the user interface (UI) block of the app, as demonstrated by the \alpha symbol at the top left. However, I'd like to replace the y-axis labels in the figure with similar symbols. For example, I want to replace "a1" with the symbol produced with \alpha_1. While one can typically use latex2expr or manually create expressions for a ggplot figure, I'm not sure how to approach this when the figure is produced within shiny.

library(shiny)
library(ggplot2)
library(ggridges)

ui <- fluidPage(
  withMathJax(),
  titlePanel("Example"),
  
  sidebarLayout(
    sidebarPanel(
      numericInput(
        "alpha1",
        label = withMathJax("\\(\\alpha_{1}\\)"),
        value = 1,  min = 0, max = 500
      )),
    
    mainPanel(plotOutput("fig"))
    
  )
)

server <- function(input, output) {
  output$fig <- renderPlot({
    df <- data.frame(z = rnorm(300, mean = input$alpha1),
                     m = as.character(rep(c("a1","a2","a3"), 100)))
    ggplot(df, aes(x = z, y = m)) + geom_density_ridges()
  })
}

shinyApp(ui, server)

I tried adding scale_y_discrete to the ggplot chain, but it only gets the beta symbol correct and does not appropriately subscript.

 scale_y_discrete(labels = c(a1 = expression(paste(beta,"_{2}")), 
                             a2 = expression(withMathJax("\\(\\alpha_{1}\\)")), 
                             a3 = expression(beta)))

Solution

  • "While one can typically use latex2expr or manually create expressions for a ggplot figure, I'm not sure how to approach this when the figure is produced within shiny." It works exactly the same way.

    library(shiny)
    library(ggplot2)
    
    ui <- fluidPage(
    
        sidebarLayout(
            sidebarPanel(
                sliderInput("bins",
                            "Number of bins:",
                            min = 1,
                            max = 50,
                            value = 30)),
            mainPanel(plotOutput("distPlot"))
        )
    )
    
    server <- function(input, output) {
    
        output$distPlot <- renderPlot({
            x    <- faithful[, 2]
            ggplot(data.frame(x = x), aes(x)) + 
                geom_histogram(bins = input$bins) +
                labs(
                    x = expression(beta[2]),
                    y = expression(alpha^2))
        })
    }
    
    shinyApp(ui = ui, server = server)
    

    enter image description here