How can I change legend symbols (key glyphs) to match the plot symbols?

别等时光非礼了梦想. 提交于 2020-06-27 16:47:10

问题


I plot data points in several groups, but then add a box plot of a different variable (same unit). See the image below. How can I change the symbols in the legend to match the symbols in the plot?

The code:

p <- ggplot(data = tdata, aes( y=Temp ,x=Distance, color=Type)) +
  geom_point() +
  geom_boxplot( aes(y = Ambient,x=5,color="Ambient"))
p + facet_grid(cols = vars(Time),rows = vars(Day))

The data:

structure(list(Day = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), Time = c("a", "a", "a", 
"a", "a", "b", "b", "b", "b", "b", "a", "a", "a", "a", "a", "b", 
"b", "b", "b", "b"), Type = c("s", "f", "s", "f", "s", "f", "s", 
"f", "s", "f", "s", "f", "s", "f", "s", "f", "s", "f", "s", "f"
), Temp = c(5, 3.1, 5.9, 8.4, 5.5, 9.9, 2.2, 6.9, 2.9, 8.8, 0.6, 
2.2, 3.1, 1.4, 4, 8.4, 5.2, 2.2, 7.9, 2.7), Distance = c(1L, 
2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 
2L, 3L, 4L), Ambient = c(4.4, 6.3, 3.1, 2.5, 7.7, 7.1, 2.1, 5.1, 
9.4, 5.7, 6.3, 4.9, 0.8, 6.5, 2.1, 1.6, 4.4, 7.9, 5.3, 5.2)), row.names = c(NA, 
-20L), class = "data.frame")

F and S should be green and blue dotes respectively and Ambient must be a box plot symbol in the Legend.


回答1:


In general the symbol or glyph in the legend can be set for each geom via the argument key_glyph. For an overview of available glyphs see here. (Thanks to @Tjebo for pointing that out.)

However, with the key_glyph argument one sets the glpyh globally for the "whole" geom and legend, i.e. one can not have different glyphs for different groups.

To overcome this and get to the desired result my approach uses two legends instead which I "glue" together so that they look as one. This is achieved by adding a second legend and removing the spacing and margin of the legends via theme().

To get a second legend I use the fill aes in geom_boxplot instead of color. To mimic a mapping on color I set the fill color to white via scale_fill_manual and adjust the fill guide via guide_legend. Try this:

library(ggplot2)

p <- ggplot() + 
  geom_point(data = tdata, aes(y=Temp, x = Distance, color = Type)) + 
  geom_boxplot(data = tdata, aes(x = 5, y = Ambient, fill = "box"), color = scales::hue_pal()(3)[1]) +
  scale_fill_manual(values = "white") +
  scale_color_manual(values = scales::hue_pal()(3)[2:3]) +
  guides(fill = guide_legend(title = "Type", order = 1), color = guide_legend(title = NULL, order = 2)) +
  theme(legend.margin = margin(t = 0, b = 0), legend.spacing.y = unit(0, "pt"), legend.title = element_text(margin = margin(b = 10)))
p + facet_grid(cols = vars(Time),rows = vars(Day))

Created on 2020-06-22 by the reprex package (v0.3.0)



来源:https://stackoverflow.com/questions/62510721/how-can-i-change-legend-symbols-key-glyphs-to-match-the-plot-symbols

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!