Andrii
Andrii

Reputation: 3043

Plotly: How to make pie chart in a gray scale?

Here is R code that draws a pie chart

library(data.table)

# Data
data <- data.table(
  class = c("class 1", "class 2", "class 3", "class 4"),
  count = c(2403, 4949, 18, 570))

# Pie
data %>% plot_ly() %>% 
  add_trace(
    type = 'pie',
    labels = ~class, 
    values = ~count,
    marker = list(
      color = "rgb(211, 211, 211)",
      line = list(color = "rgb(20, 20, 20)", width = 1))
  ) %>% 
  layout(
    xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
    yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE))

It draws a "colorized" chart when I need it as gray scale.

Upvotes: 3

Views: 1443

Answers (1)

vestland
vestland

Reputation: 61094

For a flexible approach with regards to the length of your class variable, you can simply use:

colors = gray.colors(length(data$class))

Plot 1:

enter image description here

Or if you'd like other grey tones, you can specify your own using:

colors = list("rgb(80, 80, 80)", "rgb(120, 120, 120)", "rgb(160, 160, 160)", "rgb(160, 160, 160)")

Plot 2:

enter image description here

Complete code:

library(data.table)
library(dplyr)
library(plotly)

# Data
data <- data.table(
  class = c("class 1", "class 2", "class 3", "class 4"),
  count = c(2403, 4949, 18, 570))

# Pie
data %>% plot_ly() %>% 
  add_trace(
    type = 'pie',
    labels = ~class, 
    values = ~count,
    marker = list(
      #colors = list("rgb(120, 120, 120)", "rgb(160, 160, 160)", "rgb(180, 180, 180)", "rgb(220, 220, 220)"),
      colors = gray.colors(length(data$class)),
      line = list(color = "rgb(20, 20, 20)", width = 1))
  ) %>% 
  layout(
    xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
    yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE))

Upvotes: 4

Related Questions