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