带有

时间:2018-07-24 13:20:42

标签: r ggplot2 legend

我正在使用geom_raster和geom_text在绘图中的每个彩色矩形上放一个字母。我也希望这封信也出现在图例中的颜色框的顶部,但不知道如何显示。

我尝试将show.legend=TRUE添加到geom_text,但这会在每个图例键中导致字母“ a”,而不是所需的字符。

所需结果如下:

Desired result

以下是用于重现基本情节的代码:

library(tidyverse)
d <-tribble(
    ~a, ~b, ~c,
    "a", "l", "A",
    "a", "r", "F",
    "b", "l", "Q",
    "b", "r", "R"
)

ggplot(data=d, aes(x=a, y=b, fill=c)) +
    geom_raster(na.rm=TRUE) +
    geom_text(aes(label=c), size=3, na.rm=TRUE) 

输出:

example without desired labels

这可能与以下问题有关:https://github.com/tidyverse/ggplot2/issues/2004,但是也许有解决方法?

2 个答案:

答案 0 :(得分:3)

您可以改用geom_point,并用scale_shape_manual(values = d$c) 将点的形状指定为字母

# We have to remove legend text and label with theme
ggplot(d, aes(a, b, fill = c, shape = c)) +
    geom_raster() +
    geom_point(size = 3) +
    scale_shape_manual(values = d$c) +
    theme(legend.text = element_text(size = 0),
          legend.title = element_text(size = 0))

this post

答案 1 :(得分:1)

您可以在将ggplot对象转换为grob之后对其进行破解:

# store the original ggplot object as p
p <- ggplot(data=d, aes(x=a, y=b, fill=c)) +
  geom_raster(na.rm=TRUE) +
  geom_text(aes(label=c), size=3, na.rm=TRUE, show.legend = TRUE) 

# convert to grob
gp <- ggplotGrob(p)

grid::grid.draw(gp) # can verify the plot here. Should look the same as before.

现在,我们可以检查grob对象的层次结构,以找到合适的插槽来更改图例键。也可以通过编程方式执行此操作,但是除非您的用例涉及生成具有不同数量的图例键的许多不同图表,否则我会更容易读取控制台输出:

gp # this shows the 15th grob in gp corresponds to "guide-box" (i.e. legend)

gp$grobs[15][[1]] # this shows the the first grob of the above corresponds to "guides"

gp$grobs[15][[1]]$grobs[1][[1]] 
# this shows the 5th / 8th / 11th / 14th grobs of the above correspond to the text on legend keys

str(gp$grobs[15][[1]]$grobs[1][[1]]$grobs[5][[1]])
# each of the legend key texts is a list, with a slot for "label"

相应地更改图例键:

gp$grobs[15][[1]]$grobs[1][[1]]$grobs[5][[1]]$label <- "A"
gp$grobs[15][[1]]$grobs[1][[1]]$grobs[8][[1]]$label <- "F"
gp$grobs[15][[1]]$grobs[1][[1]]$grobs[11][[1]]$label <- "Q"
gp$grobs[15][[1]]$grobs[1][[1]]$grobs[14][[1]]$label <- "R"

# check the amended plot
grid::grid.draw(gp)

plot