在下面的示例中,我想使用条件标签。
如果薪水低,则该文本应显示在栏顶部上方。如果薪水很高,则应将其显示在栏的顶部下方(就像已经与geom_text(aes(label = text),vjust = -0.25)一样)。条件本身运行良好。但是:注释应显示为字符串,即“ low”和“ high”。但在我的情况下,有“ 1”和“ 2”。我不知道这些数字来自哪里。是否有可能将文本显示为字符串,就像包含在数据框中一样?
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)
[请尝试使用dplyr::if_else()
和NULL
而不是""
library(shiny)
library(ggplot2)
library(dplyr)
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 = if_else(salary > 10000, text, NULL)), vjust=1.5) +
geom_text(aes(label = if_else(salary < 10000, text, NULL)), vjust=-1.5)
print(plot)
})
}
shinyApp(ui, server)