强制ggplot图例在没有值时显示所有类别 [英] Force ggplot legend to show all categories when no values are present

查看:24
本文介绍了强制ggplot图例在没有值时显示所有类别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图强制 ggplot 显示图例并修复因子的颜色,即使范围内不存在任何值.

I am trying to force ggplot to show the legend and fix the colors for a factor even if no value in a range is present.

在下面的可重现示例中,图 1 在变量 X1 的每个范围内至少有一个值,并根据需要绘制.绘制每个图例标签并匹配所需的颜色.

In the reproducible example below, Figure 1 has at least one value in each range of the variable X1 and plots as desired. Each legend label is plotted and matches the desired color.

在示例 2 中,变量 Y1 在创建的每个范围中都没有值.因此,该图仅显示前 4 个图例标签并使用前 4 种颜色.

In example 2, the variable Y1 does not have a value in each of the ranges that are created. As a result, the plot only shows the first 4 legend labels and uses the first 4 colors.

有没有办法绘制这个图形,强制 ggplot 显示所有八个图例标签并修复颜色,以便 cat1 值始终为红色,cat2 值始终为蓝色等.

Is there a way to plot this figure that forces ggplot to show all eight legend labels and fix the colors so that cat1 values are always red, cat2 values are always blue, etc.

我已经尝试了所有我能想到的方法,但都没有成功.

I have tried everything I can think of without success.

-- 可重现的例子--

-- Reproducible example --

set.seed(45678)
dat <- data.frame(Row = rep(x = LETTERS[1:5], times = 10), 
                  Col = rep(x = LETTERS[1:10], each = 5),
                  Y = rnorm(n = 50, mean = 0, sd = 0.5),
                  X = rnorm(n = 50, mean = 0, sd = 2))

library(ggplot2)
library(RColorBrewer)
library(dplyr)

dat <- dat %>% mutate(Y1 = cut(Y, breaks = c(-Inf,-3:3,Inf)),
                      X1 = cut(X, breaks = c(-Inf,-3:3,Inf)))

# Figure 1
ggplot(data =  dat, aes(x = Row, y = Col)) +
  geom_tile(aes(fill = X1), color = "black") +
  scale_fill_manual(values = c("red", "blue", "green", "purple", "pink", "yellow", "orange", "blue"),
                    labels = c("cat1", "cat2", "cat3", "cat4", "cat5", "cat6", "cat7", "cat8"))

# Figure 2
ggplot(data =  dat, aes(x = Row, y = Col)) +
  geom_tile(aes(fill = Y1), color = "black") +
  scale_fill_manual(values = c("red", "blue", "green", "purple", "pink", "yellow", "orange", "blue"),
                    labels = c("cat1", "cat2", "cat3", "cat4", "cat5", "cat6", "cat7", "cat8"))

推荐答案

您应该能够在 scale_fill_manual 中使用 drop = FALSE.也就是说,

You should be able to use drop = FALSE within scale_fill_manual. That is,

ggplot(data =  dat, aes(x = Row, y = Col)) +
  geom_tile(aes(fill = Y1), color = "black") +
  scale_fill_manual(values = c("red", "blue", "green", "purple", "pink", "yellow", "orange", "blue"),
                    labels = c("cat1", "cat2", "cat3", "cat4", "cat5", "cat6", "cat7", "cat8"), 
                    drop = FALSE)

有关详细信息,请参阅?discrete_scale

这篇关于强制ggplot图例在没有值时显示所有类别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆