【问题标题】:How can I change the colour line size and shape size in the legend independently?如何独立更改图例中的颜色线大小和形状大小?
【发布时间】:2020-04-08 08:21:05
【问题描述】:

我有一个线图,我将颜色和形状组合到同一个图例中。我希望图例中的点大小更大,图例中的线保持不变,以便形状更清晰。

来自How to increase the size of points in legend of ggplot2? 我了解到可以使用+ guides(colour = guide_legend(override.aes = list(size=10))) 更改点的大小,但这也会改变行的大小。如果我添加guides(shape = guide_legend(override.aes = list(size=4)),color = guide_legend(override.aes = list(size=1))),它会说`Duplicated override.aes 被忽略,只使用第二个大小。

如何单独更改图例中的色线大小和形状大小?

示例代码:

example <- data.frame(a=c(1,2,3,1,2,3), b=c(0.1,0.2,0.3,0.4,0.5,0.6), c=c('a','a','a','b','b','b'))

ggplot(example, aes(x=a, y=b, color=c, shape=c))+
  geom_line()+
  geom_point()+
  scale_colour_manual(name="title", breaks=c("a","b"),
                      labels=c("label1","label2"),
                      values=c("#e41a1c", "#377eb8"))+
  scale_shape_manual(name="title", breaks=c("a","b"),
                     labels=c("label1","label2"),
                     values=c(15, 16))+
  guides(shape = guide_legend(override.aes = list(size=4)),
         color = guide_legend(override.aes = list(size=1)))

example plot

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    ggplot 在后台使用的 layer() 函数有一个 key_glyph 参数,您可以为其提供自定义函数。您可以使用它来使点变大,但不能使线变大。如果需要自定义线条调整,可以写一个类似的函数包裹draw_key_path()。

    library(ggplot2)
    
    example <- data.frame(a=c(1,2,3,1,2,3), b=c(0.1,0.2,0.3,0.4,0.5,0.6), c=c('a','a','a','b','b','b'))
    
    large_points <- function(data, params, size) {
      # Multiply by some number
      data$size <- data$size * 2
      draw_key_point(data = data, params = params, size = size)
    }
    
    ggplot(example, aes(x=a, y=b, color=c, shape=c))+
      geom_line()+
      geom_point(key_glyph = large_points)+
      scale_colour_manual(name="title", breaks=c("a","b"),
                          labels=c("label1","label2"),
                          values=c("#e41a1c", "#377eb8"))+
      scale_shape_manual(name="title", breaks=c("a","b"),
                         labels=c("label1","label2"),
                         values=c(15, 16))
    

    由reprex package (v0.3.0) 于 2020 年 4 月 8 日创建

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-07-12
      • 1970-01-01
      • 2022-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多