首页 > 解决方案 > 如何在着色点时将文本添加到分面图?

问题描述

我正在尝试将文本添加到我可以使用的多面图

datasets_text <- data.frame(cyl = unique(mtcars$cyl))
datasets_text$label <- c('text1','text2','text3')

mtcars <- head(mtcars)
ggplot(mtcars, aes(hp,drat))+
  geom_point()+
  facet_wrap(~cyl)+
  geom_text(size    = 2,
          data    = datasets_text,
          mapping = aes(x = Inf, y = Inf, label = label),
          hjust   = 1.05,
          vjust   = 1.5)

在此处输入图像描述

我也想给我能做的点上色

mtcars <- head(mtcars)
ggplot(mtcars, aes(hp,drat, colour=gear))+
  geom_point()+
  facet_wrap(~cyl)+

在此处输入图像描述

但是,当我将两者结合起来时

ggplot(mtcars, aes(hp,drat, colour=gear))+
  geom_point()+
  facet_wrap(~cyl)+
  geom_text(size    = 2,
          data    = datasets_text,
          mapping = aes(x = Inf, y = Inf, label = label),
          hjust   = 1.05,
          vjust   = 1.5)

我明白了Error in FUN(X[[i]], ...) : object 'gear' not found。如何在为点着色的同时向构面添加文本?

标签: rggplot2facetfacet-wrap

解决方案


您可以inherit.aes = FALSE在调用中指定geom_text

ggplot(mtcars, aes(hp,drat, colour=gear))+
    geom_point()+
    facet_wrap(~cyl)+
    geom_text(size    = 2,
              data    = datasets_text,
              mapping = aes(x = Inf, y = Inf, label = label),
              hjust   = 1.05,
              vjust   = 1.5, inherit.aes = FALSE)

在此处输入图像描述

从有关geom_text帮助文件inherit.aes中:

如果为 FALSE,则覆盖默认美学,而不是与它们结合。这对于定义数据和美学的辅助函数最有用,并且不应该从默认绘图规范继承行为


推荐阅读