如何在ggplot图例的两个部分中显示颜色?

时间:2016-10-17 19:00:01

标签: r ggplot2

我试图绘制几个不同系列的线图,其中每个系列将使用不同的线宽绘制,并且每个系列都属于确定颜色的几个组中的一个。

我努力做的是创建一个图例,显示组名称和颜色,以及每个系列名称和宽度/颜色组合。

给出一个最小的工作示例:

# Create data
names <- c("A", "B", "C", "D", "E", "F")

df <- data.frame(
  name = rep(names, 3),
  group = rep(c(rep("X", 2), rep("Y", 2), rep("Z", 2)), 3),
  x = c(rep(1, 6), rep(2, 6), rep(3, 6)),
  y = c(runif(6, 0, 1), runif(6, 1, 2), runif(6, 2, 3)),
  stringsAsFactors=FALSE
)


line.widths <- setName(runif(6, 0, 3), names)
group.colors <- setNames(c("#AA0000", "#00AA00", "#0000AA"), c("X", "Y", "Z"))
name.colors <- setNames(c(rep("#AA0000", 2), rep("#00AA00", 2), rep("#0000AA", 2)),
                        names)

现在情节:

library(ggplot2)

# Names and groups separately
ggplot(df, aes_string(x="x", y="y", group="name")) +
  geom_line(aes(size=name, color=group)) +
  scale_size_manual(values=line.widths) + 
  scale_color_manual(values=group.colors)

Six lines, with three different colors and three different line sizes.

我的问题是,是否可以将组颜色添加到图例的name部分,而不会丢失group部分。

谢谢!

1 个答案:

答案 0 :(得分:1)

令人难以置信地关闭(并且感谢你研究和尝试过的问题)。您只需在图例中添加override.aes,如下所示:

ggplot(df, aes_string(x="x", y="y", group="name")) +
  geom_line(aes(size=name, color=group)) +
  scale_size_manual(values=line.widths) + 
  scale_color_manual(values=group.colors) +
  guides(size = guide_legend(override.aes = list(col = name.colors)))

enter image description here