Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

custom colors in R Plotly

Tags:

r

plotly

r-plotly

I'm currently a beginner in Plotly and have a problem I can't seem to solve. I have my plotly stacked bar chart but I don't know how to color each individual category. I am currently using R.

This is my current stacked bar chart: enter image description here

My current code is:

p = plot_ly(x, x = day, y = count, type = "bar", group = status) %>% layout(barmode = "stack", showlegend = T)

I've tried using the "color = " parameter and also markers, but nothing correctly colors my graph.

like image 233
DLo Avatar asked Feb 24 '16 11:02

DLo


People also ask

How do you choose colors in Plotly?

Color Sequences in Plotly ExpressBy default, Plotly Express will use the color sequence from the active template's layout. colorway attribute, and the default active template is plotly which uses the plotly color sequence. You can choose any of the following built-in qualitative color sequences from the px. colors.


1 Answers

You need to specify a factor for the color parameters, and then a vector of colours for the colors parameter.

Here is a simple solution. Note the ordering required on the data frame before plotting.

require(dplyr)
require(plotly)

set.seed(42)

df <- data.frame(x = rep(LETTERS[1:5], 3), 
                 y = rexp(15, rate = 0.5),
                 z = c(rep("Adam", 5), rep("Arthur", 5), rep("Ford", 5)))
df <- arrange(df, desc(z))

plot_ly(df, 
        x = x, 
        y = y, 
        color = z, 
        colors = c("grey50", "blue", "red"), 
        type = "bar") %>% 
    layout(barmode = "stack")

The ordering on the data frame matters strangely. I would have thought plot_ly would use the order of the levels but it doesn't.

EDIT: This example uses plotly 3.x.x. If you use plotly 4.x.x or above, this code may not work as is. See here for more details: https://www.r-bloggers.com/upgrading-to-plotly-4-0-and-above/

like image 92
mal Avatar answered Oct 05 '22 13:10

mal