【问题标题】:Set only one aesthetic to show up in ggplo2 legend只设置一种美学出现在ggplot2图例中
【发布时间】:2018-04-12 11:49:53
【问题描述】:

我有一个同时使用线条类型和颜色美学的数据集。图例显示了两种美学,但我只希望图例本身具有一种美学(颜色或线条类型)。

这也适用于另一个数据集,其中我只希望四行中的一行比其余行大,这是我在 geom_line 美学中使用 ifelse 语句所做的,但实际的 ifelse 语句显示在图例中.

我从mtcars 数据集中举了一个例子,我希望只显示颜色。

library(tidyverse)
mtcars <- as.tibble(mtcars)

mtcars$gear <- as.factor(mtcars$gear)
mtcars$cyl <- as.factor(mtcars$cyl)

mtcars1 <- mtcars %>%
  arrange(gear) %>%
  ggplot(aes(x = qsec, group = 1)) +
  geom_point(aes(y=disp, group = cyl, color = cyl)) +
  geom_line(aes(y=disp, group = cyl, color = cyl, linetype = cyl)) + 
  scale_color_manual(values=c("#000000", "#E69F00", "#56B4E9")) + 
  labs(title = "MTCARS Example", colour="Cylinder",x= "x",y="Disp") 
print(mtcars1)

是否可以操纵图例只显示一种美学?

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    试试

    mtcars1 + guides(color = "none")
    mtcars1 + guides(linetype = "none")
    

    【讨论】:

      【解决方案2】:

      简答:使用相同的图例名称:labs(colour = "Cylinder", linetype = "Cylinder)

      # Simplified version of the same plot
      library(ggplot2)
      # 1. All aes specified in main ggplot2 function
      # 2. In aes x always goes first, y always goes second,
      #    you don't need to write x = ..., y = ...
      ggplot(mtcars, aes(qsec, disp, color = cyl, linetype = cyl)) +
          geom_point() +
          geom_line() +
          scale_color_manual(values = c("#000000", "#E69F00", "#56B4E9")) + 
          # For "tidier" code use same order as in aes 
          # (except for main title, or subtitle)
          labs(title = "MTCARS Example", 
               x = "x",
               y = "Disp", 
               color = "Cylinder", 
               linetype = "Cylinder")
      

      如果您想使用组合图例,您必须对 aes 使用相同的变量(您已经这样做了)。默认情况下,图例名称为 cyl。但是,当您更改单一美学的名称时(color = "Cylinder"ggplot2 认为您正在使用两个不同的变量。因此,您必须为这样的情节重命名这两种美学:

      PS.:我简化了您的 ggplot2 函数。不要多次重写y=disp, color = cyl,将它们设置在主ggplot2函数中。此外,您不需要group(知道您在那里尝试做什么)。

      【讨论】:

      • 谢谢@PoGibas。我在需要的地方读了一些。 (我对 R 很陌生)为什么有人会使用 group
      • @Jordan 看看这个question(tl;dr 用它作为因素)。此外,您不需要需要print 来显示情节,只需输入mtcars1
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-12-07
      • 1970-01-01
      • 2019-02-07
      • 2016-08-21
      • 1970-01-01
      • 2012-05-08
      • 1970-01-01
      相关资源
      最近更新 更多