调整来自 ggpot2 scale_fill_brewer(palette = "Greys")

时间:2021-02-17 10:11:31

标签: r ggplot2

我用下面的数据和代码创建了一个图。我想更改用于条形的灰度值,使它们都变暗一步。但是,我在 ?scale_fill_brewer 中看不到任何内容,这将允许我执行此操作。有没有简单的解决方案来解决这个问题?

数据:

counts_truth  <- structure(list(x_label = c("Truth ECOST = 0.52", "Truth ECOST = 0.39", 
"Truth ECOST = 0.26", "Truth ECOST = 0.13", "Truth ECOST = 0.00", 
"Truth ECOST = 0.52", "Truth ECOST = 0.39", "Truth ECOST = 0.26", 
"Truth ECOST = 0.13", "Truth ECOST = 0.00"), treatment = structure(c(1L, 
1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L), .Label = c("control", "treatment"
), class = "factor", scores = structure(c(control = 0.424793388429752, 
treatment = 0.498594189315839), .Dim = 2L, .Dimnames = list(c("control", 
"treatment")))), percentage = c(0.163636363636364, 0.272727272727273, 
0.427272727272727, 0.6, 0.781818181818182, 0.319587628865979, 
0.360824742268041, 0.474226804123711, 0.701030927835051, 0.88659793814433
), remove = c("Truth ECOST ", "Truth ECOST ", "Truth ECOST ", 
"Truth ECOST ", "Truth ECOST ", "Truth ECOST ", "Truth ECOST ", 
"Truth ECOST ", "Truth ECOST ", "Truth ECOST "), ECOST = c("0.52", 
"0.39", "0.26", "0.13", "0.00", "0.52", "0.39", "0.26", "0.13", 
"0.00")), row.names = c(NA, -10L), class = c("data.table", "data.frame"
))

library(ggplot2)
counts_truth %>% 
ggplot(aes(x = ECOST, y = percentage, fill = treatment, label=sprintf("%0.2f", round(percentage, digits = 2)))) + 
geom_col(position = 'dodge') + 
geom_text(position = position_dodge(width = .9),    # move to center of bars
          vjust = -0.5,    # nudge above top of bar
          size = 5) +           
scale_fill_brewer(palette = "Greys") + 
theme_bw()  

enter image description here

1 个答案:

答案 0 :(得分:1)

一种快速解决方案是使用 scale_fill_grey 将灰色连续体调整为稍微暗一些。根据您的数据集,以下内容会使绘图变暗。

根据需要调整 startend 参数。它们的范围在 0(黑色)和 1(白色)之间。

counts_truth %>% 
    ggplot(aes(x = ECOST, y = percentage, fill = treatment, label=sprintf("%0.2f", round(percentage, digits = 2)))) + 
    geom_col(position = 'dodge') + 
    geom_text(position = position_dodge(width = .9),    # move to center of bars
              vjust = -0.5,    # nudge above top of bar
              size = 5) +           
    scale_fill_grey(start = 0.8, end = 0.5) +
    theme_bw()