生成具有稍暗线条的填充图,然后填充填充颜色

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

为了产生不那么令人分心的箱形图,为fillcolor设置类似的色标会很不错。如何在没有猜测的情况下实现这一目标?

r ggplot2 rgb
2个回答
4
投票

Predefined colors (scale_*_manual)

使用colorspace::darken()的简单解决方案

这是我猜的最简单的解决方案:

library(ggplot2)
library(colorspace)

hex_colors = c(
  setosa = "#80adf7", 
  versicolor = "#96ef8f", 
  virginica = "#f4a1df")

g = ggplot(iris, aes(x = Species, y = Sepal.Length, fill = Species, color = Species))
g + geom_boxplot() + 
  scale_fill_manual(values = hex_colors) + 
  scale_color_manual(values = darken(hex_colors, amount = 0.3))

手动计算颜色

如果您想要更多控制,可以将HEX转换为RGB并稍微减少红色,绿色和蓝色的所有值。您还可以将它转换为HSV,并通过将rgb2hsv添加到pipelne并调用hsv而不是rgbat结束,使用色调,饱和度和光度值更容易。

library(ggplot2)
library(magrittr)
library(purrr)

hex_colors = c(
  setosa = "#80adf7", 
  versicolor = "#96ef8f", 
  virginica = "#f4a1df")

dark_colors = hex_colors %>% 
  col2rgb %>% #convert HEX colors to RGB Matrix
  "*"(0.7) %>% # make each component "darker"
  apply(2, lift_dv(rgb, maxColorValue = 255)) # Convert each column to HEX again

g = ggplot(iris, aes(x = Species, y = Sepal.Length, fill = Species, color = Species))
g + geom_boxplot() + 
  scale_fill_manual(values = hex_colors) + 
  scale_color_manual(values = dark_colors)

两种方法都会产生以下结果:

Boxplots

Automatic colors (scale_*_discrete)

scale_*_discrete适用于HSL色彩空间。我们可以手动定义亮度。

library(ggplot2)
g = ggplot(iris, aes(x = Species, y = Sepal.Length, fill = Species, color = Species))
g + geom_boxplot() + 
  scale_fill_discrete(l = 70) + # a bit brighter
  scale_color_discrete(l = 50) # a bit darker

boxplot 2


2
投票

另一种解决方案就是将alpha()传递给scale_FOO_manual。有了它我们只需要指定想要的alpha和颜色值:

library(ggplot2)

color <- c("red", "blue", "green")
alpha_color <- 1
alpha_fill <- 0.2

ggplot(iris, aes(Species, Sepal.Length, fill = Species, color = Species)) +
  geom_boxplot() + 
  scale_fill_manual(values = alpha(color, alpha_fill)) + 
  scale_color_manual(values = alpha(color, alpha_color))

enter image description here

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