r - ggplot 按因子和渐变着色
问题描述
我正在尝试绘制一个在两个变量(一个因子和一个强度)上着色的图。我希望每个因素都是不同的颜色,并且我希望强度是白色和该颜色之间的渐变。
到目前为止,我已经使用了诸如对因子进行刻面、将颜色设置为两个变量之间的交互、将颜色设置为因子并将 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)
我想要实现的是看起来最像使用 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)
)
接下来使用这种争吵来获得十六进制颜色:
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
绘制它:
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)))
推荐阅读
- haskell - Haskell中的分类结构
- mysql - MySQL 默认值为 NULL
- asp.net - Asp.Net 菜单来自 Sql Server“MenuItemClick”事件未触发
- r - R 到 Oracle 连接
- r - 在 R 的 ergm 包中,如果我想模拟具有同质性/聚类的图,我应该输入什么模拟网络?
- video - ffmpeg - 在两次之间向视频添加文本
- solid-principles - 单一责任原则与开闭原则
- javascript - 如何使用 Mailjet 进行身份验证而不会出现与 node_modules 相关的错误?
- laravel - 航海者 Laravel axios 获得 405
- csv - 将 csv 导入 sqlite3 插入失败