LauraP
LauraP

Reputation: 311

How can I change the colors of the slices in pie charts in plotly for r using hexadecimal strings?

This is my pie chart as of right now:

library(plotly)
library(RColorBrewer)


P <- data.frame (labels = c("A", "B", "C", "D", "E"),
             values = c(5, 8, 3, 4, 9))

plot_ly(P, labels = labels, values = values, type = "pie",
    marker = list(colors=c("lightskyblue", "deepblue", "dodgerblue", "midnightblue", "powderblue")),
    textinfo="value",
    textposition="outside") 

I wanted to change its colors with hexidecimal strings so I could use palettes from RColorBrewer. Thank you in advance!

Upvotes: 3

Views: 6291

Answers (2)

Sowmya S. Manian
Sowmya S. Manian

Reputation: 3833

Exploring RColorBrewer package

   library(RColorBrewer)

To see list of functions inside RColorBrewer package

   ls("package:RColorBrewer")
   #  [1] "brewer.pal"         "brewer.pal.info"    "display.brewer.all"
   #  [4] "display.brewer.pal"

To display all color schemes

   display.brewer.all()

To get the Blues hexadecimal strings

   brewer.pal(9,"Blues")
   # [1] "#F7FBFF" "#DEEBF7" "#C6DBEF" "#9ECAE1" "#6BAED6" "#4292C6" "#2171B5"
   # [8] "#08519C" "#08306B"

   brewer.pal(10,"Blues")
   # [1] "#F7FBFF" "#DEEBF7" "#C6DBEF" "#9ECAE1" "#6BAED6" "#4292C6" "#2171B5"
   # [8] "#08519C" "#08306B"
   # Warning message:
   # In brewer.pal(10, "Blues") :
   # n too large, allowed maximum for palette Blues is 9
   # Returning the palette you asked for with that many colors

To View the Blues palatte

  display.brewer.pal(9,"Blues")

There are limits on the number of colours you can get, but if you want to extend the Sequential or Diverging groups you can do so with the colorRampPalatte command, for example :

  colorRampPalette(brewer.pal(9,”Blues”))(100)

Example for divergent, qualitative and sequential schemes. The Spectral, Set2 , Reds, these names can be seen using command mentioned above display.brewer.all(). You can use some other schemes from the list.

 display.brewer.pal(4,"Spectral")
 brewer.pal(4,"Spectral")
 # [1] "#D7191C" "#FDAE61" "#ABDDA4" "#2B83BA"

 display.brewer.pal(4,"Set2")
 brewer.pal(4,"Set2")
 # [1] "#66C2A5" "#FC8D62" "#8DA0CB" "#E78AC3"

 display.brewer.pal(4,"Reds")
 brewer.pal(4,"Reds")
 # [1] "#FEE5D9" "#FCAE91" "#FB6A4A" "#CB181D"

Upvotes: 3

dww
dww

Reputation: 31452

Just put the hex values into the strings, preceded with a hash (pound symbol) #. the first two digits in hex are for red, the next 2 for green, then 2 digits for blue (#RRGGBB). Optionally you can add an extra two digits for the alpha (transparency) (#RRGGBBAA).

e.g

plot_ly(P, labels = labels, values = values, type = "pie",
    marker = list(colors=c("#556677", "#AA3344", "#772200", 
                           "#11AA22", "#AA231B88")), # the last color has alpha value set.
    textinfo="value",
    textposition="outside") 

Upvotes: 6

Related Questions