繁体   English   中英

如何使用 ggplot2 和 RColorBrewer 根据值范围预定义图例颜色?

[英]How to predefine legend colours based on value range using ggplot2 and RColorBrewer?

我有一些来自我计算 STEN 分数的测试的数据。 我的目标是以圆形条形 plot 的形式可视化此数据,并希望根据 STEN 分数范围设置颜色渐变。 例如,0-2 的分数表示非常浅的颜色,2.1-4 表示浅色,4.1-6 表示中等,6.1-8 表示深色,8.1-10 表示非常暗。 我下面的代码使用RColorBrewer package 和"YlGn"调色板,但我坚持如何根据上述示例预定义配色方案并将其设置在 plot 图例中。 下面的示例生成一个圆形条 plot,其中包含 4.8 的最低 STEN 分数,因此我希望将其反映为中等颜色,目前它是最浅的颜色。 我基本上希望图例显示所有五个 STEN 分数范围,而不管某人的数据分数是否在每个范围内。 希望这是有道理的。

library(tidyverse)
library(RColorBrewer)

set.seed(50)
dat <- data.frame(
  
  par = paste("par", 1:15),
  test_1 = round(rnorm(15, mean = 30, sd = 5), 1),
  test_2 = round(rnorm(15, mean = 30, sd = 5), 1),
  test_3 = round_any(rnorm(15, mean = 90, sd = 5), 2.5),
  test_4 = round(rnorm(15, mean = 5.4, sd = 0.3), 1),
  test_5 = round(rnorm(15, mean = 17, sd = 1.5), 1)
  
)

sten_dat <- dat %>%
  mutate_if(is.numeric, scale) %>%
  mutate(across(c(2:6), ~ . * 2 + 5.5)) %>%
  mutate(across(where(is.numeric), round, 1)) %>%
  pivot_longer(!par, names_to = "test", values_to = "sten") %>%
  filter(par == "par 1")

ggplot(sten_dat) +
  geom_col(aes(x = str_wrap(test), y = sten, fill = sten),
           position = "dodge2", alpha = 0.7, show.legend = TRUE) +
  coord_polar() +
  scale_y_continuous(limits = c(-1, 11), breaks = seq(0, 10, 2)) +
  scale_fill_gradientn(colours = brewer.pal(name = "YlGn", n = 5))`

只需为您的填充比例添加limits

ggplot(sten_dat) +
  geom_col(aes(x = str_wrap(test), y = sten, fill = sten),
           position = "dodge2", alpha = 0.7, show.legend = TRUE) +
  coord_polar() +
  scale_y_continuous(limits = c(-1, 11), breaks = seq(0, 10, 2)) +
  scale_fill_gradientn(colours = brewer.pal(name = "YlGn", n = 5),
                       limits = c(0, 10))

在此处输入图像描述

如果您希望 colors 以您描述的方式清楚地“装箱”,您可以使用scale_fill_stepn而不是scale_fill_gradientn

ggplot(sten_dat) +
  geom_col(aes(x = str_wrap(test), y = sten, fill = sten),
           position = "dodge2", alpha = 0.7, show.legend = TRUE) +
  scale_y_continuous(limits = c(-1, 11), breaks = seq(0, 10, 2)) +
  scale_fill_stepsn(colours = brewer.pal(name = "YlGn", n = 5),
                    limits = c(0, 10), breaks = 0:5 * 2) +
  geomtextpath::coord_curvedpolar() +
  theme_minimal() +
  theme(axis.text.x = element_text(size = 16, face = 2),
        panel.grid.major.x = element_blank())

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM