mardi 10 décembre 2019

R Shiny: Conditional labeling with geom_text

In the following example I want to make use of conditional labeling.

If the salary is low, the text should be shown above the top of the bar. If the salary is high, it should be shown below the top of the bar (like it is already with geom_text(aes(label=text), vjust=-0.25)). The condition itself is working very well. But: The annotation should be shown as a string, i.e. "low", and "high". But in my case there is "1" and "2". I don't know where these numbers come from. Is there the possibility to show the text as string like it is contained in the data frame?

library(ggplot2)

ui <- fluidPage(

  titlePanel("conditional label"),
  sidebarLayout(
    sidebarPanel(),
    mainPanel(plotOutput(outputId = "distPlot")
    )
  )
)

server <- function(input, output) {

  output$distPlot <- renderPlot({

    employee <- c('John Doe','Peter Gynn','Jolie Hope')
    salary <- c(5000, 9000, 12000)
    text <- c('low', 'low', 'high')
    df <- data.frame(employee, salary, text)

    plot <- ggplot(data=df, aes(x=employee, y=salary), color="black") +
      geom_bar(color="black", stat="identity", show.legend = FALSE) +
      scale_y_continuous(limits=c(0,13000)) +
      geom_text(aes(label=text), vjust=-0.25) +
      geom_text(aes(label = ifelse(salary > 10000, text, "")), vjust=1.5) +
      geom_text(aes(label = ifelse(salary < 10000, text, "")), vjust=-1.5)

    print(plot)


  })

}

shinyApp(ui, server)

Aucun commentaire:

Enregistrer un commentaire