我正在尝试创建一个闪亮的应用程序,用户可以在其中选择随时间绘制三列中的哪一列,由三个候选者的百分比组成。到目前为止,实际的情节非常完美,但我想添加一些颜色,使Cand_1得到一条蓝色的线,Cand_2得到一条绿色的线,而Cand_3得到一条红色的线。我尝试在变量名周围使用带"和不带"的Plot + scale_colour_manuall = "c("Cand_1" = "blue", "Cand_2" = "green", "Cand_3" = "red)
,也尝试在aes()
中使用if
,这样:
Plot <- Plot + geom_line(aes(month, !! sym(input$cand)), group = 1, if(input$cand == "Cand_1){
colour = "blue"}
if(input$cand == "Cand_2"){colour = "green"}
if(input$cand == "Cand_2"){colour = "red})
但它们都不起作用,要么给出错误Attempted to create layer with no stat
,要么只是忽略了论证者。
整个代码如下所示:
library(shiny)
library(tidyverse)
setwd("")
Data <- read.csv("Data.csv", stringsAsFactors = F)
# Define UI
ui <- fluidPage(
# Application title
titlePanel("Candidates"),
# Sidebar with a select input
sidebarLayout(
sidebarPanel(
selectInput("Cand",
"Candidates",
choices = colnames(Data)[2:4], multiple = TRUE)
),
mainPanel(
plotOutput("LederPlott"),
textOutput("length")
)
)
)
# Define server logic required to draw plot
server <- function(input, output) {
output$CandPlott <- renderPlot({
Plot <- ggplot(Data)
if(length(input$Cand) == 1){
Plot <- Plot + geom_line(aes(month, !! sym(input$Cand)), group = 1)
}
if(length(input$Cand) == 2){
Plot <- Plot + geom_line(aes(month, !! syms(input$Cand)[[1]]), group = 1)+
geom_line(aes(month, !! syms(input$Cand)[[2]]), group = 1)
}
if(length(input$Cand) == 3){
Plot <- Plot + geom_line(aes(month, !! syms(input$Cand)[[1]]), group = 1)
Plot <- Plot + geom_line(aes(month, !! syms(input$Cand)[[2]]), group = 1)
Plot <- Plot + geom_line(aes(month, !! syms(input$Cand)[[3]]), group = 1)
}
Plot <- Plot + theme_classic() + ylab("%") + ggtitle("%God")
Plot
})
output$length <- renderText(input$Cand)
}
# Run the application
shinyApp(ui = ui, server = server)
下面是一些样本数据:
Month Cand_1 Cand_2 Cand_3
2019-02-01 60,7 90,1 86,2
2019-03-01 58,9 90,2 80,3
2019-04-01 47,3 88,3 84,6
2019-05-01 54,5 87,3 90
2019-06-01 50,6 86 89
2019-07-01 49,8 84,2 87,1
你不能这样分配颜色,
Plot <- Plot + geom_line(aes(month, !! sym(input$cand)), group = 1, if(input$cand == "Cand_1){
colour = "blue"}
if(input$cand == "Cand_2"){colour = "green"}
if(input$cand == "Cand_2"){colour = "red})
因为颜色是aes((的一个参数。它必须出现在顶级,如下所示:
Plot <- Plot + geom_line(aes(month, !! sym(input$cand)), group = 1, colour = <your decision here>)
但是,这个参数还有另一个用途。它的作用是用不同的颜色给不同的群体上色。您想要的是每次一个变量。因此,出于这种目的,它也不会起作用。
您需要的是将color=
参数放在geom_line()
调用中,但放在aes()
:之外
Plot <- Plot + geom_line(aes(month, !! sym(input$cand)), group = 1),
colour = if(input$cand == "Cand_1") "blue" else
if(input$cand == "Cand_2")"green" else
if(input$cand == "Cand_3") "red")
还有一些较短的方法:
color.list <- list(Cand_1 = "blue", Cand_2 = "green", Cand_3 = "red")
Plot <- Plot + geom_line(aes(month, !! sym(input$cand)), group = 1),
colour = color.list[[input$cand]])