首页 > 解决方案 > ggplot2 - 拆分一个图例(两个色标)并删除另一个

问题描述

我在配置情节图例时遇到了很多麻烦ggplot2。我有两个数据框:

require(ggplot2)
mat <- rep(c("None", "wood", "steel"), each = 4)
feet = rep(seq(0,3), 3)
load = c(3:6, 4:7, 5:8)

soil <- data.frame(
  feet = feet,
  test = rep(1:3, each = 4),
  load = c(0.1, 0.2, 0.3, 0.04,
           0.5, 0.6, 0.7, 0.44,
           0.8, 0.9, 1.0, 0.74)
)

dat <- rbind(
  data.frame(
    feet = feet,
    mat = mat,
    load = c(3:6, 4:7, 5:8),
    SF = FALSE
  ),
  data.frame(
    feet = feet,
    mat = mat,
    load = c(6:9, 7:10, 8:11),
    SF = TRUE
  )
)

我想要一个带有图例dat$mat和图例的情节soil$test

myplot <- ggplot(dat, aes(x = load, y = feet)) +
  geom_line(aes(color = mat, linetype = SF)) +
  geom_path(dat = soil, aes(x = load, y = feet, color = factor(test)))

myplot

在此处输入图像描述

我不想要名为SF. 另外,我想将命名的图例拆分mat为两个图例,来自data.framemat的 (values = "none", "wood", "steel") 和来自datdata.frame 的test(values = 1, 2, 3) soil.

我已经尝试过theme(legend.position = "none"),以及许多其他各种代码组合,如果我将它们全部列出,它们会填满页面。感谢您提供的任何帮助。

标签: rggplot2aeslegend

解决方案


更新-此答案中提供了更好的选择。我会离开这个,因为在某些情况下可能仍然需要使用虚假美学的黑客传说。

正如@MM 正确所说的那样- ggplot 不想为一种美学画两个图例。

我真的希望您不会经常需要执行以下 hack 之类的操作:

做一个假的美学(我选择alpha),并手动定义每条线的颜色。override.aes然后手动 更改您的图例键。

如果您要显示的数据不止这些,请考虑使用不同的可视化/数据分离方式。一个非常好的事情是刻面

library(ggplot2)
library(dplyr)

ggplot(dat, aes(x = load, y = feet)) +
  geom_line(aes(color = mat, linetype = SF)) +
  geom_path(dat = filter(soil,test ==1), 
             aes(x = load, y = feet, alpha = factor(test)), color = 'red') +
  geom_path(dat = filter(soil,test ==2), 
             aes(x = load, y = feet, alpha = factor(test)), color = 'brown') +
  geom_path(dat = filter(soil,test ==3), 
             aes(x = load, y = feet, alpha = factor(test)), color = 'green') +
  scale_alpha_manual(values = c(rep(1,3))) +
  scale_linetype(guide = FALSE) +
  guides( alpha = guide_legend(title = 'test', 
                               override.aes = list(color = c('red','brown','green'))))


推荐阅读