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')
>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


