【问题标题】:Placing ggplot2 shape annotations into titles将 ggplot2 形状注释放入标题中
【发布时间】:2017-11-29 17:28:21
【问题描述】:

我正在尝试将形状(和填充颜色)插入标题/副标题,但找不到这样做的语法:

    library(tidyverse) 
    D <-diamonds %>%  filter(color=="D") %>%sample_frac(0.1) 
    G <-diamonds %>%  filter(color=="G") %>% sample_frac(0.1)

    ggplot(D, aes(x=carat, y=price))+  
    geom_jitter(data=G)+geom_point(shape=6)+
      geom_jitter(data=D)+geom_point(shape=22, fill='red')+
     labs(title, "This is a title", 
    subtitle= 
    "D diamonds (insert shape 22 fill red) and G diamonds (shape 6 color black)",
     caption = "what I want is to insert the shape and fill color into the (sub)title")

建议? Annotate 似乎只在情节空间中工作。

【问题讨论】:

  • 您能否制作一个图例并将其移动到标题下方的左上角作为解决方法?

标签: r ggplot2 title shape subtitle


【解决方案1】:

处理图像的一种可能解决方法是使用图例来获得所需的外观。这涉及到首先制作一个传奇。我使用color 美学来制作图例,每个点图层一个。我在aes 中给出的字符串将是标签图例。

我通过scale_color_manual 修改图例。这涉及以正确的顺序获取标签并设置颜色。此外,我使用guide_legend 选项将标签移动到键框的左侧(它们默认在右侧)并为点获取正确的形状和填充。

然后,在theme中,可以将图例移动到左上角,键框可以用白色代替灰色填充并缩小尺寸,并且可以缩小图例周围的空间。

这一切看起来像:

ggplot(D, aes(x = carat, y = price))+  
     geom_jitter(data = G) +
     geom_point(data = G, aes(color = "and G diamonds"), shape = 6) +
     geom_jitter() +
     geom_point(aes(color = "D diamonds"), shape = 22, fill='red') +
     labs(title = "This is a title") +
     scale_color_manual(name = NULL, values = c("black", "black"), 
                        limits = c("D diamonds", "and G diamonds"),
                        guide = guide_legend(label.position = "left",
                                             override.aes = list(shape = c(22, 6),
                                                                 fill = c("red", "black")) ) ) +
     theme(legend.direction = "horizontal",
           legend.position = "top",
           legend.justification = "left",
           legend.key = element_rect(fill = "white"),
           legend.key.size = unit(.5, "mm"),
           legend.margin = margin(b = 0, 0, 0, 0) )

从ggplot2的current development version开始,ggplot2_2.1.0.9001,在theme中有一个legend.box.spacing选项,可以减少绘图和图例之间的空间。我觉得legend.box.spacing = unit(2, "mm") 看起来不错。

【讨论】:

  • 这很优雅!而不是我的方法 - 本质上是作弊并试图通过隐身将图例潜入标题中,而是建议将图例简单地移动到字幕空间中。聪明的!给猫剥皮的多种方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-10
相关资源
最近更新 更多