gpt4 book ai didi

r - 设置颜色以显示清晰的数字

转载 作者:行者123 更新时间:2023-12-04 00:17:33 24 4
gpt4 key购买 nike

在这个特定 viridis 选项的条形图中,是否可以设置一组颜色,即使对于刻度的较暗选项,也可以清楚地显示图表内的数字?

library(ggplot2)
Year <- c(rep(c("2006-07", "2007-08", "2008-09", "2009-10"), each = 4))
Category <- c(rep(c("A", "B", "C", "D"), times = 4))
Frequency <- c(168, 259, 226, 340, 216, 431, 319, 368, 423, 645, 234, 685, 166, 467, 274, 251)
Data <- data.frame(Year, Category, Frequency)
ggplot(Data, aes(x = Year, y = Frequency, fill = Category, label = Frequency)) +
geom_bar(stat = "identity") +
geom_text(size = 3, position = position_stack(vjust = 0.5)) + scale_fill_viridis_d(option = "magma")

最佳答案

利用我从 scales::show_col 学到的技巧,您可以像这样根据填充自动选择文本颜色:

library(ggplot2)
Year <- c(rep(c("2006-07", "2007-08", "2008-09", "2009-10"), each = 4))
Category <- c(rep(c("A", "B", "C", "D"), times = 4))
Frequency <- c(168, 259, 226, 340, 216, 431, 319, 368, 423, 645, 234, 685, 166, 467, 274, 251)
Data <- data.frame(Year, Category, Frequency)

# Trick from scales::show_col
hcl <- farver::decode_colour(viridisLite::magma(length(unique(Category))), "rgb", "hcl")
label_col <- ifelse(hcl[, "l"] > 50, "black", "white")

ggplot(Data, aes(x = Year, y = Frequency, fill = Category, label = Frequency)) +
geom_bar(stat = "identity") +
geom_text(aes(color = Category), size = 3, position = position_stack(vjust = 0.5), show.legend = FALSE) +
scale_color_manual(values = label_col) +
scale_fill_viridis_d(option = "magma")

编辑

我最近学到的第二个选项是使用 ggplot2::after_scaleprismatic::best_contrast 来自动选择具有最佳对比度的文本颜色,如下所示:

library(prismatic)

ggplot(Data, aes(x = Year, y = Frequency, fill = Category, label = Frequency)) +
geom_bar(stat = "identity") +
geom_text(aes(color = after_scale(
prismatic::best_contrast(fill, c("white", "black"))
)),
size = 3, position = position_stack(vjust = 0.5), show.legend = FALSE
) +
scale_fill_viridis_d(option = "magma")

关于r - 设置颜色以显示清晰的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62800823/

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