为了产生不那么令人分心的箱形图,为fill
和color
设置类似的色标会很不错。如何在没有猜测的情况下实现这一目标?
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
而不是rgb
at结束,使用色调,饱和度和光度值更容易。
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)
两种方法都会产生以下结果:
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
另一种解决方案就是将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))