我正在尝试绘制一个对两个变量(一个因子和一个强度)进行着色的图。我希望每个因素都是不同的颜色,并且我希望强度是白色和该颜色之间的渐变。
到目前为止,我已经使用了诸如对因子进行分面等技术,将颜色设置为两个变量之间的相互作用,并将颜色设置为因子并将 alpha 设置为强度以近似我想要的效果。然而,我仍然觉得一个图上的白色和全色之间的渐变最能代表这一点。
有谁知道如何在不自定义创建所有颜色渐变并仅设置它们的情况下执行此操作?此外,是否有一种方法可以使图例的工作方式就像图表使用颜色和 Alpha 一样,而不是像为交互设置颜色时那样列出所有颜色?
到目前为止我已经尝试过:
ggplot(diamonds, aes(carat, price, color=color, alpha=cut)) +
geom_point()
ggplot(diamonds, aes(carat, price, color=interaction(color, cut))) +
geom_point()
ggplot(diamonds, aes(carat, price, color=color)) +
geom_point() +
facet_wrap(~cut)
Run Code Online (Sandbox Code Playgroud)
我想要实现的是看起来最像使用 alpha 的图形,但我想要白色和该颜色之间的渐变,而不是透明度。此外,我希望图例看起来像使用颜色和 alpha 的图例,而不是交互图等中的图例。
我通常使用的方法是操纵因子值,以便我可以将它们插入到函数中hcl()。
首先,一些原始数据:
library(tidyverse)
raw_data <-
diamonds %>%
filter(price < 500, color %in% c("E", "F", "G")) %>%
mutate(
factor = factor(color),
intensity = cut,
interaction = paste(factor, intensity)
)
Run Code Online (Sandbox Code Playgroud)
接下来使用这种争论来获取十六进制颜色:
color_values <-
raw_data %>%
distinct(factor, intensity, interaction) %>%
arrange(factor, intensity) %>%
mutate(
interaction = fct_inorder(interaction),
# get integer position of factors
factor_int = as.integer(factor) - 1,
intensity_int = as.integer(intensity),
# create equal intervals for color, adding in some padding so we avoid extremes of 0, 1
hue_base = factor_int / (max(factor_int) + 0.5),
light_base = 1 - (intensity_int / (max(intensity_int) + 2)),
# using ^^^ to feed into hcl()
hue = floor(hue_base * 360),
light = floor(light_base * 100),
# final colors
hex = hcl(h = hue, l = light)
)
color_values %>% filter(intensity == "Good")
# factor intensity interaction factor_int intensity_int hue_base light_base hue light hex
# <ord> <ord> <fct> <dbl> <int> <dbl> <dbl> <dbl> <dbl> <chr>
# E Good E Good 0 2 0 0.714 0 71 #D89FA9
# F Good F Good 1 2 0.4 0.714 144 71 #81BA98
# G Good G Good 2 2 0.8 0.714 288 71 #BDA4D2
Run Code Online (Sandbox Code Playgroud)
绘制它:
ggplot(df, aes(x, y, color = interaction)) +
geom_count() +
facet_wrap(~factor) +
scale_color_manual(
values = color_values$hex,
labels = color_values$interaction
) +
guides(color = guide_legend(override.aes = list(size = 5)))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1801 次 |
| 最近记录: |