其他資源:
scale類函數(shù)的命名方式
ggplot中scale名字沃斤、美學(xué)屬性和函數(shù)列表
limits
??需要注意:設(shè)置limits之后,limits之外的數(shù)據(jù)點(diǎn)都會(huì)強(qiáng)制為NA谚鄙,不會(huì)在plot中展示。在之后進(jìn)行的stat運(yùn)算都不會(huì)包含這些超出的數(shù)據(jù)點(diǎn)疚鲤。繪圖過(guò)程中也會(huì)有警告信息啸如,請(qǐng)務(wù)必關(guān)注。
??默認(rèn)limits通過(guò)計(jì)算data variables的range得到成翩,包括position scales(如x和y aesthetics)和non-position scales(如color aesthetic)觅捆。
??應(yīng)用1:來(lái)自同一底層data或不同底層data的多個(gè)plot進(jìn)行比較時(shí),需要設(shè)置相同的limits麻敌,實(shí)現(xiàn)方法有如下幾種:
# 來(lái)自同一底層data栅炒,用分面實(shí)現(xiàn)
ggplot(mpg, aes(displ, hwy)) + geom_point() + facet_wrap(vars(year))
# 來(lái)自不同底層data,用scale_x/y_continous()實(shí)現(xiàn)
consistent_limits <- function(p){
p <- p + scale_x_continuous(limits = c(1, 7)) + scale_y_continuous(limits = c(10, 45))
}
mpg_99 <- mpg %>% filter(year == 1999)
mpg_08 <- mpg %>% filter(year == 2008)
base_99 <- ggplot(mpg_99, aes(displ, hwy)) + geom_point()
base_99_final <- consistent_limits(base_99)
base_08 <- ggplot(mpg_08, aes(displ, hwy)) + geom_point()
base_08_final <- consistent_limits(base_08)
# 來(lái)自不同底層data,用lims()實(shí)現(xiàn)赢赊,lims()的好處是寫(xiě)法簡(jiǎn)單還可以同時(shí)設(shè)置多個(gè)aesthetics
base_99_final <- base_99 + lims(x = c(1, 7), y = c(10, 45))
base_08_final <- base_08 + lims(x = c(1, 7), y = c(10, 45))
# 對(duì)離散型變量乙漓,用scale_x/y_discrete()實(shí)現(xiàn)
diamonds_cut <- ggplot(diamonds, aes(cut)) + geom_bar()
diamonds_cut + scale_x_discrete(limits=c("Fair","Good","Very Good"))
# 對(duì)離散型變量,用lims()實(shí)現(xiàn)
diamonds_cut + lims(x=c("Fair","Good","Very Good"))
??應(yīng)用2:來(lái)自同一底層data或不同底層data的多個(gè)plot需要保持圖例一致释移,實(shí)現(xiàn)方法如下:
# 來(lái)自同一底層data叭披,用分面實(shí)現(xiàn),分面總是能保持plots在各個(gè)方面的一致性
ggplot(mpg, aes(displ, hwy, color=fl)) + geom_point() + facet_wrap(vars(year))
# 來(lái)自不同底層data秀鞭,用scale_color_discrete()實(shí)現(xiàn)
base_99 <- ggplot(mpg_99, aes(displ, hwy, color=fl)) + geom_point()
base_08 <- ggplot(mpg_08, aes(displ, hwy, color=fl)) + geom_point()
base_99_legend <- base_99 + scale_color_discrete(limits=c("c", "d", "e", "p", "r"))
base_08_legend <- base_08 + scale_color_discrete(limits=c("c", "d", "e", "p", "r"))
# 來(lái)自不同底層data趋观,用lims()實(shí)現(xiàn)
base_99_legend <- base_99 + lims(color=c("c", "d", "e", "p", "r"))
base_08_legend <- base_08 + lims(color=c("c", "d", "e", "p", "r"))
??應(yīng)用3: 來(lái)自不同底層data,需要保持color的一致性锋边,又想在legend中只展示各自底層data中有的分類皱坛。
# 使用scale_color_discrete()的breaks參數(shù)實(shí)現(xiàn),同時(shí)labels參數(shù)還可以改變legend的標(biāo)簽
base_99 + scale_color_discrete(limits=c("c", "d", "e", "p", "r"),breaks=c("d","p","r"),labels=c("diesel","premium","regular"))
base_08 + scale_color_discrete(limits=c("c", "d", "e", "p", "r"),labels=c("compressed","diesel","ethanol","premium", "regular"))