基于轴颜色的ggplot图例

Posted

技术标签:

【中文标题】基于轴颜色的ggplot图例【英文标题】:ggplot legend based on axis colors 【发布时间】:2021-08-31 14:39:27 【问题描述】:

我正在尝试根据我设置的 y 轴的颜色在 ggplot 中创建一个图例。

有谁知道是否有一种方法可以根据图中本身不存在的数据手动创建图例?

下面是情节和代码的玩具示例。在这个图中,我绘制了 3 个不同日期的学生成绩图。学生的姓名根据他们所在的班级进行着色。我想知道我是否可以添加一个额外的图例,以绿色显示“A 班”,以紫色显示“B 班”。

作为补充说明,我意识到日子并不好过。目前我并不担心这一点。

谢谢!

library(tidyverse)

name <- c("Mike", "Mike","Mike",
          "Sam","Sam","Sam", 
          "Max","Max","Max", 
          "Sarah","Sarah","Sarah") 
date <- c("Monday", "Wednesday", "Friday",
          "Monday", "Wednesday", "Friday",
          "Monday", "Wednesday", "Friday",
          "Monday", "Wednesday", "Friday")
grade <- c(100, 98, 93, 
           92, 64, 90, 
           80, 88,70,
           90,94,100)
clas-s-room <- c("Class A", "Class A","Class A", 
               "Class A", "Class A","Class A", 
               "Class B", "Class B","Class B", 
               "Class B", "Class B","Class B")

df <- data.frame(cbind(name, date, grade, clas-s-room)) %>%
  mutate(grade = as.integer(grade),
         clas-s-room = as.factor(clas-s-room))


plot <- ggplot(df, aes(y=name, x=date, fill= grade < 90)) + 
  geom_tile() +
  scale_fill_manual(name = " ", values = c( "turquoise3","lightgrey"), labels = c("Above 90","At or below 90" )) +
  theme(axis.text.y = element_text(color = ifelse(levels(df$clas-s-room) %in% "Class A", "Green", "Purple"))) +
  guides(size = "none", color = "none", alpha = "none") 

【问题讨论】:

你也许可以使用ggtext 【参考方案1】:

你可以facet_wrap

plot <- ggplot(df, aes(y=name, x=date, fill= grade < 90)) + 
  geom_tile() +
  scale_fill_manual(name = " ", values = c( "turquoise3","lightgrey"), labels = c("Above 90","At or below 90" )) +
  theme(axis.text.y = element_text(color = ifelse(levels(df$clas-s-room) %in% "Class A", "Green", "Purple"))) +
  guides(size = "none", color = "none", alpha = "none") 

plot +  facet_wrap(~clas-s-room)

facet_grid

plot + facet_grid(rows = vars(clas-s-room))

【讨论】:

以上是关于基于轴颜色的ggplot图例的主要内容,如果未能解决你的问题,请参考以下文章

R语言ggplot2可视化配置图例(legend)标签色彩的升序或者反序(reverse)实战:ggplot2可视化默认图例标签色彩(升序,颜色越来越深)可视化配置图例标签颜色反序(颜色越来越浅)

ggplot2:图例混合颜色和隐藏线用于预测图

带有颜色和图例的简单 ggplot2 情况

更改 ggplot2 中条形图和图例的默认颜色

在 ggplot 中结合颜色和线型图例

ggplot2中散点图的图例(无颜色)