在子数据集的图中创建公共图例

时间:2017-01-04 07:06:37

标签: r ggplot2

我正在阅读Hadley Wickham的ggplot2 book,并希望对我的其中一个练习的解决方案发表评论:

第6.5.1节 练习1

以下代码创建了两个mpg数据集图。修改代码以使图例和轴匹配,而不使用构面!

fwd <- subset(mpg, drv == "f")
rwd <- subset(mpg, drv == "r")
ggplot(fwd, aes(displ, hwy, colour = class)) + geom_point()
ggplot(rwd, aes(displ, hwy, colour = class)) + geom_point()

enter image description here 这是我的解决方案:

ggplot(fwd, aes(displ, hwy, colour = class)) +
  geom_point() +
  lims(x = c(0, 7), y = c(0, 45)) +
  geom_point(aes(colour = class), alpha = 0, data = mpg) +
  guides(colour = guide_legend(override.aes = list(alpha = 1)))

ggplot(rwd, aes(displ, hwy, colour = class)) +
  geom_point() +
  lims(x = c(0, 7), y = c(0, 45)) +
  geom_point(aes(colour = class), alpha = 0, data = mpg) +
  guides(colour = guide_legend(override.aes = list(alpha = 1)))

enter image description here 我觉得我的想法很聪明,但对大型数据集来说效率不高。有没有更直接的方法来解决这个问题?或者这是练习的目标是什么?

1 个答案:

答案 0 :(得分:2)

只需使用drop = FALSE即可保留所有系数级别。

mpg$class <- as.factor(mpg$class) # convert to factor
fwd <- subset(mpg, drv == "f")
rwd <- subset(mpg, drv == "r")
ggplot(fwd, aes(displ, hwy, colour = class)) + geom_point() + scale_colour_discrete(drop=FALSE)
ggplot(rwd, aes(displ, hwy, colour = class)) + geom_point() + scale_colour_discrete(drop=FALSE)

enter image description here