在ggplot2中,从线图例中删除多余的点

问题描述 投票:0回答:1

我有这个情节:

library(ggplot2)
ggplot(iris,
       aes(
           x = Petal.Length,
           y = Petal.Width,
           color = Species,
           linetype = Species,
           shape = Species
       )) +
    geom_count(alpha = 0.20) +
    geom_smooth(method = "lm", se = FALSE) + 
    labs(
        color = "Species (Line)",
        linetype = "Species (Line)",
        shape = "Species (Points)"
    )  +
    guides(
        size = "none"
        )
#> `geom_smooth()` using formula = 'y ~ x'

创建于 2023-11-02,使用 reprex v2.0.2

我正在尝试格式化图例,以便有一个具有点形状(也按颜色)的图例和一个单独的线型图例(也按颜色)。

我实际上得到的是一个仅用于形状(无颜色)的图例和一个具有彩色点的线型图例。我已经尝试了我能想到的图例标签的每一次迭代,但无济于事。

问题: 保持其他一切不变,我怎样才能摆脱物种(线)图例中的那些点?以及如何为形状添加颜色?

r ggplot2 plot tidyverse scatter-plot
1个回答
0
投票

您需要删除颜色指南并覆盖形状和线型指南的美观:

library(ggplot2)

ggplot(iris,
       aes(
         x = Petal.Length,
         y = Petal.Width,
         color = Species,
         linetype = Species,
         shape = Species
       )) +
  geom_count(alpha = 0.20) +
  geom_smooth(method = "lm", se = FALSE) + 
  labs(
    linetype = "Species (Line)",
    shape = "Species (Points)"
  )  +
  guides(
    size = "none",
    color = "none",
    shape = guide_legend(override.aes = list(alpha = 1, 
                                             color =  scales::hue_pal()(3))),
    linetype = guide_legend(override.aes = list(color =  scales::hue_pal()(3)))
  )

© www.soinside.com 2019 - 2024. All rights reserved.