Изменение цвета на графике в блестящем R - PullRequest
0 голосов
/ 07 октября 2019

Почему цвет линий графика меняется каждый раз, когда я выбираю элемент из списка? Пример ниже. Я выбираю A из списка 2018 года и A из списка 2019 года, тогда я получаю желтые графики. Но когда я добавляю B с 2018 года, я получаю другие цветные линии. Можете ли вы мне помочь?

enter image description here enter image description here

Мой код:

library(plotly)
library(dplyr)
library(shiny)
library(readxl)
library(tidyr)

df1 <- data.frame(Month = rep(month.abb[1:12],10,replace = TRUE), Product = rep(LETTERS[1:10], each = 12), 
                  Value = sample(c(0:300),120, replace = T), stringsAsFactors = F)
df2 <- data.frame(Month = rep(month.abb[1:12],10,replace = TRUE), Product = rep(LETTERS[1:10], each = 12), 
                  Value = sample(c(0:300),120, replace = T), stringsAsFactors = F)

trend_pal <-  c('red','blue', 'yellow', 'green') #Palette

# UI
ui <- fluidPage(
    column(
        6,fluidRow(column(6, selectizeInput("All", "Year: 2018", multiple = T,choices = unique(df1$Product), 
                                            options = list(maxItems = 5, placeholder = 'Choose a product:'))),
                   column(6, selectizeInput("All2", "Year: 2019", multiple = T,choices = unique(df2$Product), 
                                            options = list(maxItems = 5, placeholder = 'Choose a product:'))))
    ),
     column(
        12,fluidRow(column(12, plotlyOutput('plot'))
    )
   ) 
)


# Server code
server <- function(input, output) {

    outVar <- reactive({
        df1 %>%
            filter(Product %in% input$All) %>%
            arrange(Month) %>%
            droplevels()
    })

    outVar2 <- reactive({
        df2 %>%
            filter(Product %in% input$All2) %>%
            arrange(Month) %>%
            droplevels()
    })

    output$plot <- renderPlotly({
        plot_ly(data=outVar(), x=~Month,  y = ~Value,
                type = 'scatter', mode = 'lines', legendgroup = "1",
                color = ~Product , colors = trend_pal) %>%
        add_trace(data=outVar2(), x=~Month,  y = ~Value,
            type = 'scatter', mode = 'lines', legendgroup = "2",
            color = ~Product , colors = "Dark2")  %>%
            layout(legend = list(orientation = 'h'))         
    }) 
}

# Return a Shiny app object
shinyApp(ui = ui, server = server)
...