krish krish -4 years ago 321
R Question

How to change the default colors in plotly chart?

I am creating a plotly stacked bar chart and depending on the filters my dataset changes.

The dataset look like:

tabNew <- structure(list(Group = c("2016-11", "2016-12", "2017-01", "2017-
02", "2017-03"),
`Did Not Meet Expectations` = c(3, 0.8, 1.5, 0.8, 1.7),
`Exceeded Expectations` = c(45, 50.6, 32.3, 49.5, 55.6),
`Met Expectations` = c(51.2, 48.5, 66.2, 49.5, 42.4),
Unacceptable = c(0.7, 0, 0, 0.1, 0.2)),
.Names = c("Group", "Did Not Meet Expectations",
"Exceeded Expectations", "Met Expectations", "Unacceptable"),
row.names = c(NA, -5L), class = "data.frame")


The code to plot the chart is as below:

x <- list(
title = "Time"
)
y <- list(
title = "Percent"
)

p <- plot_ly(tabNew, x = ~Group, y = ~`Unacceptable`, colors = c("red", "yellow", "green", "blue"),
name = 'Unacceptable', type = 'scatter', mode = 'lines') %>%
add_trace(y = ~`Did Not Meet Expectations`, name = 'Did Not Meet Expectations') %>%
add_trace(y = ~`Met Expectations`, name = 'Met Expectations') %>%
add_trace(y = ~`Exceeded Expectations`, name = 'Exceeded Expectations') %>%
layout(xaxis = x, yaxis = y)


The chart looks like:

enter image description here

This dataset is an example where the
Group
represent
Months
. Sometimes based on filters, the
Group
can represents
Quarters
and in such cases, there may not be all other columns. So there are chances that we have only
Did Not Meet Expectations
,
Exceeded Expectations
and
Met Expectations
.

In either case, I do not want the default colors. I want
Unacceptable
if its there to be shown by
Red
,
Did Not Meet Expectations
if available to be shown as
Yellow
and likewise
Met Expectations
by
Blue
and
Exceeded Expectations
as
Green
. Is there a way to specify this order?

Answer Source
require(plotly)

df <- data.frame(
  Group        = c("2016-11", "2016-12", "2017-01", "2017-02", "2017-03"),
  DidNot       = c(3, 0.8, 1.5, 0.8, 1.7),
  Exceeded     = c(45, 50.6, 32.3, 49.5, 55.6),
  Met          = c(0.7, 0, 0, 0.1, 0.2),
  Unacceptable = c(0.7, 0, 0, 0.1, 0.2)
  )

plot_ly(df, x = ~Group) %>%
  add_trace(y = ~Exceeded, 
            name = "Exceeded Expectations", 
            type = "scatter", 
            mode = "lines",
            line = list(color = "green")) %>%
  add_trace(y = ~Unacceptable, 
            name = "Unacceptable", 
            type = "scatter", 
            mode = "lines",
            line = list(color = "red")) %>%
  layout(xaxis = list(title = "Time"),
         yaxis = list(title = "Percent"))

This code produces:

enter image description here

I modified your dataframe syntax to be neater to me and I obviously did not draw all the lines for you but you get the picture.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download