代码之家  ›  专栏  ›  技术社区  ›  Jellz

ggplot2中多个图例中的下标

  •  5
  • Jellz  · 技术社区  · 7 年前

    为了使我的图形适合黑白打印,我将一个变量与“shape”、“lty”、“color”映射在一起。

    ggplot(df, aes(x=time, y=mean, 
                   shape=quality, 
                   lty=quality,
                   color=quality))
    

    我得到的数字是, enter image description here 我想将部分图例作为下标,代码如下:

    labels=c(expression(Pol[(Art)]), expression(Pol['(Aca-)']), expression(Pol['(Aca-)']))
    

    不幸的是,当我把“标签”放在颜色或形状上时,它使图例非常复杂,比如,

    enter image description here

    是否可以将“形状”、“颜色”、“lty”映射到一个变量,并设置下标,但将它们保存在一组图例中?

    1 回复  |  直到 7 年前
        1
  •  7
  •   Brian    3 年前

    要更改分类比例的标签,请使用 scale_*_discrete(labels = ...) . 在这里,你只需要这样做 color , shape linetype .

    您应该避免使用 lty = 通常地这个同义词允许与base R兼容,但它并没有得到普遍支持 ggplot2 .

    我更改了标签,以更接近我认为您的意思(第三个条目现在是“Aca+”而不是“Aca-”),并使它们更好地左对齐(通过在第一个标签上添加一个不可见的“+”,以创建适当的间距)。

    lab1 <- c(expression(Pol[(Art)*phantom("+")]),
              expression(Pol['(Aca-)']), 
              expression(Pol['(Aca+)']))
    
    library(ggplot2)
    
    ggplot(mtcars, 
           aes(wt, mpg, 
               color = factor(cyl), 
               shape = factor(cyl), 
               linetype = factor(cyl))) +
      geom_point() +
      stat_smooth(se = F) +
      scale_color_discrete(labels = lab1) +
      scale_shape_discrete(labels = lab1) +
      scale_linetype_discrete(labels = lab1)
    

    enter image description here

    如果您发现自己需要重复这样的函数的精确副本,有两种解决方法:

    1. 重新标记数据本身- -

    2. 使用 purrr::invoke_map 迭代函数的步骤


    library(purrr)
    
    ggplot(mtcars, 
           aes(wt, mpg, 
               color = factor(cyl), 
               shape = factor(cyl), 
               linetype = factor(cyl))) +
      geom_point() +
      stat_smooth(se = F) +
      invoke_map(list(scale_color_discrete, 
                      scale_linetype_discrete, 
                      scale_shape_discrete),
                 labels = lab1)
    

    更新:

    这种方法基本上是好的,但现在 expression(...) syntax有一个更好的选择,基于优秀的降价 {ggtext} 包裹: https://github.com/wilkelab/ggtext

    要更改此方法,请使用标签向量(可选,命名),如下所示:

    library(ggtext)
    
    lab1 <- c(
      `4` = "Pol<sub>(Art)</sub>",
      `6` = "Pol<sub>(Aca-)</sub>", 
      `8` = "Pol<sub>(Aca+)</sub>"
    )
    

    然后将这一行添加到主题中:

      ... +
      theme(
        legend..text = element_markdown()
      )
    

    与其他方法相比,其优势在于:

    1. markdown语法更易于在线搜索帮助
    2. 现在,这些标签可以作为列存储在实际数据中,而不是将它们分别传递给每个geom

    您可以使用该新列作为美学映射[ ggplot(..., aes(color = my_new_column, linetype = my_new_column, ...) ]而不必使用 purrr::invoke 方法