gpt4 book ai didi

r - ggplot 按因子和梯度颜色

转载 作者:行者123 更新时间:2023-12-03 08:54:34 24 4
gpt4 key购买 nike

我正在尝试绘制一个在两个变量(一个因子和一个强度)上着色的图。我希望每个因素都是不同的颜色,并且我希望强度是白色和该颜色之间的渐变。

到目前为止,我已经使用了一些技术,例如对因子进行分面、将颜色设置为两个变量之间的相互作用,以及将颜色设置为因子并将 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)))

enter image description here

关于r - ggplot 按因子和梯度颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56552388/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com