我正在阅读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()
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)))
答案 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)