2

I have a variable Channel which is factor with levels A,B,C. If you run my shiny up level A is red points level B green points and level C blue points. When I uncheck A level to make it disspear colous for B and C change and that is what I want to prevents. So every level should have it's colour. I tried to play around a bit with scale manual etc but no success.

########### UI.R
library(shiny)

shinyUI(fluidPage(
    titlePanel("Hello Shiny!"),
    sidebarLayout(
        sidebarPanel(
            checkboxGroupInput(inputId="check1_1", label="Select channel", choices=c("a","b","c"),
                               selected=c("a","b","c"))
        ),

        mainPanel(
            plotOutput("myplot")
        )
    )
))

########## Server.R
shinyServer(function(input, output) {

df<-data.frame(Channel=sample(letters[1:3],100,replace = TRUE),
                        x=runif(100),
                        y=runif(100))

df1<-reactive({

    y<-as.factor(input$check1_1)
    df1<-df[which(df$Channel %in% y), ]
}) 
output$myplot<-renderPlot({
    ggplot(df1(),aes(x = x,y = y,colour=Channel))+geom_point(size=6)
})  


})
Tomas H
  • 713
  • 4
  • 10
  • 1
    A couple ways to do it, shown [here](http://stackoverflow.com/questions/21322819/generating-a-consistent-dynamic-color-palette-in-ggplot-within-a-loop) and [here](http://stackoverflow.com/questions/19068432/ggplot2-how-to-use-same-colors-in-different-plots-for-same-factor#) – aosmith Jul 01 '16 at 17:59
  • 1
    I haven't tested it with your code, but I think you can just add `+ scale_color_discrete(drop=FALSE)` to your ggplot code. This will work regardless of which rows are removed from the data, so long as the underlying levels of the factor don't change. – eipi10 Jul 01 '16 at 18:06
  • eipi thanks works greatly – Tomas H Jul 01 '16 at 18:15

1 Answers1

2

You can just add + scale_color_discrete(drop=FALSE) to your ggplot code. This will work regardless of which rows are removed from the data, so long as the underlying levels of the factor don't change.

eipi10
  • 91,525
  • 24
  • 209
  • 285