27 Working with colors | Interactive web-based data visualization with R, plotly, and shiny (2024)

The JavaScript library underlying plotly (plotly.js) has it’s own support for specifying colors, which is different from how R specifies colors. It currently supports:

If you use plot_ly() and directly specify a plotly.js color attribute (e.g.marker.color), you can use any of these formats. Figure 27.1 uses the the hsl format:

plot_ly(x = iris$Petal.Length, marker = list(color = "hsl(0, 100%, 50%)"))

27 Working with colors | Interactive web-based data visualization with R, plotly, and shiny (1)

FIGURE 27.1: Specifying a color in plotly.js’ supported format.

If you’re doing something specific to R, like using ggplotly() and/or the top-level color/stroke argument in plot_ly(), you’ll need to be careful to about specifying colors in way that R and plotly can understand. For example, at least currently, you can’t specify an hsl string in this way:

plot_ly(x = 1, y = 1, color = I("hsl(0, 100%, 50%)"))#> Error in grDevices::col2rgb(x, alpha = TRUE): invalid color name 'hsl(0, 100%, 50%)'

Just like in ggplot2, you’ll have to specify a color in one of the following ways:

  • A hexadecimal string of the form “#rrggbb” or “#rrggbbaa”.
  • Named colors (e.g.“blue”). All supported names are listed in colors().
  • An NA for transparent.

This doesn’t imply that you can’t work in other colorspaces though (e.g.rgb, rgba, hsl, or hsl). The colorspace package provides a nice way to create colors in any of these colorspaces and provides a hex() function that you can use to convert any color to a hexidecimal format (Ihaka et al. 2019).

library(colorspace)red <- hex(HLS(0, 0.5, 1))plot_ly(x = iris$Petal.Length, color = I(red))

If you’d like to learn more about how to use the color argument as well as specify different types of color palettes, see Section 3.

References

Ihaka, Ross, Paul Murrell, Kurt Hornik, Jason C. Fisher, Reto Stauffer, Claus O. Wilke, Claire D. McWhite, and Achim Zeileis. 2019. colorspace: A Toolbox for Manipulating and Assessing Colors and Palettes. https://CRAN.R-project.org/package=colorspace.

27 Working with colors | Interactive web-based data visualization with R, plotly, and shiny (2024)
Top Articles
Latest Posts
Article information

Author: Sen. Ignacio Ratke

Last Updated:

Views: 5867

Rating: 4.6 / 5 (56 voted)

Reviews: 95% of readers found this page helpful

Author information

Name: Sen. Ignacio Ratke

Birthday: 1999-05-27

Address: Apt. 171 8116 Bailey Via, Roberthaven, GA 58289

Phone: +2585395768220

Job: Lead Liaison

Hobby: Lockpicking, LARPing, Lego building, Lapidary, Macrame, Book restoration, Bodybuilding

Introduction: My name is Sen. Ignacio Ratke, I am a adventurous, zealous, outstanding, agreeable, precious, excited, gifted person who loves writing and wants to share my knowledge and understanding with you.