Create new customized color palette for a stacked bar chart with R ggplot

50 Views Asked by At

I'm creating a stacked bar chart with ggplot and want to customize the colors.

pp<- ggplot(dt.data, aes(x = delivMonth, y = val, fill = comp)) +
            geom_bar(stat = "identity") +
            labs(x = "", y = "<b>Val", title = "<b>Stacked Bar Chart") +
            scale_fill_manual(values = terrain.colors(length(unique(dt.data$comp)))) +
            theme_minimal() +
            theme(legend.position = "right") +
            guides(fill = guide_legend(title = "<b>Comp")) +
            scale_x_date(date_labels = "%Y-%m", date_breaks = "1 month") +
            theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
            theme(plot.title = element_text(hjust = 0.5)) +
            theme(legend.key.size = unit(0.7, "cm"))

ggplotly(pp, tooltip = c("x", "y", "fill"), hovermode = "x")

At the moment I'm using the terrain.colors() for my color palette.

Here are some sample colors I want to have in my new color palette:

green <- "#00943b"
berggreen <- "#006551"
technoblue <- "#2f53a0"
signalyellow <- "#fdc300"
hellgrey <- "#f0f0f0"
mittelgrey <- "#a8a8a8"
dunkelgrey <- "#6f6f6f"
dunkelblue <- "#123374"
hellblue <- "#7da9db"
dunkeltuerkis <- "#007982"
helltuerkis <- "#63c3d1"

How can I do this?

1

There are 1 best solutions below

0
stefan On BEST ANSWER

Here is a possible implementation of a custom color palette and a corresponding fill scale which make use of colorRampPalette for the case where more colors are needed:

green <- "#00943b"
berggreen <- "#006551"
technoblue <- "#2f53a0"
signalyellow <- "#fdc300"
hellgrey <- "#f0f0f0"
mittelgrey <- "#a8a8a8"
dunkelgrey <- "#6f6f6f"
dunkelblue <- "#123374"
hellblue <- "#7da9db"
dunkeltuerkis <- "#007982"
helltuerkis <- "#63c3d1"

pal_custom <- function() {
  pal <- c(
    green, berggreen, technoblue, signalyellow, hellgrey,
    mittelgrey, dunkelgrey, dunkelblue, hellblue,
    dunkeltuerkis, helltuerkis
  )

  function(n) {
    if (n > length(pal)) {
      pal <- colorRampPalette(pal)(n)
    }
    pal <- pal[seq_len(n)]

    pal
  }
}

scale_fill_custom <- function(name = waiver(), ..., aesthetics = "fill") {
  discrete_scale(aesthetics, name = name, palette = pal_custom(), ...)
}

library(ggplot2)

set.seed(123)

dat <- data.frame(
  fill = sample(LETTERS[1:5], 100, replace = TRUE)
)

ggplot(dat, aes(factor(1), fill = fill)) +
  geom_bar() +
  scale_fill_custom()



dat <- data.frame(
  fill = sample(LETTERS[1:20], 100, replace = TRUE)
)

ggplot(dat, aes(factor(1), fill = fill)) +
  geom_bar() +
  scale_fill_custom()