使用 R ggplot 为堆叠条形图创建新的自定义调色板

问题描述 投票:0回答:1

我正在使用

ggplot
创建堆叠条形图并想要自定义颜色。

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

目前我正在使用

terrain.colors()
作为我的调色板。

以下是我想要在新调色板中使用的一些示例颜色:

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

我该怎么做?

r ggplot2 plotly bar-chart color-palette
1个回答
1
投票

这是自定义调色板和相应填充比例的可能实现,在需要更多颜色的情况下使用

colorRampPalette

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

© www.soinside.com 2019 - 2024. All rights reserved.