Colors and groups with less than three members

I’m creating a Shiny application with a combined line and bar chart in Plotly.

Right now it looks like this

But when I (in Shiny) choose less than three members of the group I get

Such that the colors are not correctly chosen. This is one among other errors. I know it is because plotly internally calls RColorBrewer that throws an error whenever n < 3 as is seen in this warning:

Warning in RColorBrewer::brewer.pal(N, “Set2”) :
minimal value for n is 3, returning requested palette with 3 different levels

Does anyone know how to work around this problem? I am not interested in upgrading to the development version, since this causes other problems for other plotly charts in my shiny app.

Code below:

p <- plot_ly(df.real,
        x=df.real$Date,
        y=df.real$value,
        type = "bar",
        color = df.real$Product,
        colors = as.character(df.real$Color),
        hoverinfo = "text",
        text = paste("Product:", df.real$Product, "<br>",
                     "Budget:", df.budg$value, "<br>",
                     "Realised:", df.real$value, "<br>",
                     "Date:", df.real$Date, "<br>",
                     "Information:", df.real$descr
                     ))
p <-  add_trace(p,
            x = df.budg$Date,
            y = df.budg$value,
            mode = "lines",
            color = df.budg$Product,
            colors = as.character(df.budg$Color),
            hoverinfo = "text",
            text = paste("Product:", df.budg$Product, "<br>",
                         "Budget:", df.budg$value, "<br>",
                        "Realised:", df.real$value, "<br>",
                       "Date:", df.budg$Date, "<br>",
                      "Information:", df.real$descr))

Best

Sounds like a bug to me.

I’d recommend posting a new issue on https://github.com/ropensci/plotly/issues

So I realised this bug was due to some unused levels in my dataframe!