Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

plotly stacked area graph custom colours from named vector

I am trying to use custom colours with a dataset in Plotly. The named vector works from a line graph and other graphs, but doesn’t for the stacked area graph. Any ideas?

Also posted here: https://community.rstudio.com/t/plotly-stacked-area-graph-custom-colours-from-named-vector/153342

library(plotly)
library(tidyverse)
library(palmerpenguins) # for the dataset

penguins_cols <- c("Adelie" = "blue",
                   "Gentoo" = "red",
                   "Chinstrap" = "green")

# works for line graphs
plot_ly(penguins,
        colors = penguins_cols) %>%
  add_trace(x = ~bill_length_mm,
            y = ~bill_depth_mm,
            color = ~species,
            type = "scatter",
            mode = "lines+markers")


# doesn't work for area graphs
plot_ly(penguins,
        colors = penguins_cols) %>%
  add_trace(x = ~bill_length_mm,
            y = ~bill_depth_mm,
            fillcolor = ~species,
            mode = "none",
            stackgroup = 'one')

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

enter image description here

>Solution :

Perhaps there is more direct way but from the docs setting the colors via fillcolor seems to be the way to go, i.e. use fillcolor = ~penguins_cols[species] and set the names for the legend entries via name = ~species.

library(ggplot2)
library(plotly)
library(palmerpenguins)

penguins_cols <- c("Adelie" = "blue",
                   "Gentoo" = "red",
                   "Chinstrap" = "green")

plot_ly(penguins) %>%
  add_trace(x = ~bill_length_mm,
            y = ~bill_depth_mm,
            name = ~species,
            fillcolor = ~penguins_cols[species],
            mode = "none",
            type = "scatter",
            stackgroup = 'one')
#> Warning: Ignoring 2 observations

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading