此文為自己翻譯,原文鏈接請看How to expand color palette with ggplot and RColorBrewer
直方圖(histogram)和柱狀圖(bar)是數據分析展示的一部分。如果圖是由R語言ggplot2包中函數geom_histogram()或者geom_bar()來制作,則柱狀圖看起來是這樣的:
library(ggplot2)
ggplot(mtcars, aes(factor(cyl), fill=factor(cyl))) +
geom_bar()
ggplot函數的優雅在於對可視化公式簡單而緊湊的表達,同時隱藏了默認情況下許多假設選項。隱藏並不意味着缺乏,因為大多數選擇只是一步之遙。例如,對於顏色選擇,使用scale函數族中的其中一種選擇scale_fill_brewer():
ggplot(mtcars, aes(factor(cyl), fill=factor(cyl))) +
geom_bar() +
scale_fill_brewer()
參數 palette 控制着 scale_fill_brewer() 中的顏色選擇:
ggplot(mtcars, aes(factor(cyl), fill=factor(cyl))) +
geom_bar() +
scale_fill_brewer(palette="Set1")
Palettes在包RColorBrewer中 - 運行 display.brewer.all() 可以看到所有的選擇:
有3類調色板(palettes)- sequential, diverging, and qualitative - 每一類調色板包含8到12種顏色(可以利用
brewer.pal.info 或者 ?RColorBrewer看到更多的細節)。
好奇的讀者可能注意到如果柱狀圖包含13或者更多的柱子,我們可能會有下面的圖中的麻煩:
ggplot(mtcars) +
geom_bar(aes(factor(hp), fill=factor(hp))) +
scale_fill_brewer(palette="Set2")
的確, length(unique(mtcars$hp)) 有 22 個唯一值,然而調色板 Set2 只有 8 中顏色。調色板中的顏色缺乏導致了ggplot如下的警告:
Warning message:
In RColorBrewer::brewer.pal(n, pal) : n too large, allowed maximum for palette Set2 is 8
Returning the palette you asked for with that many colors
RColorBrewer為我們提供了一種通過使用構造函數colorRampPalette插入現有調色板來生成更大調色板的方法。它生成實際工作的函數:它們通過插入現有的調色板來構建具有任意數量顏色的調色板。要將調色板Set1插入到22種顏色(顏色數量存儲在colourCount變量中,以供后續示例):
colourCount = length(unique(mtcars$hp))
getPalette = colorRampPalette(brewer.pal(9, "Set1"))
ggplot(mtcars) +
geom_bar(aes(factor(hp)), fill=getPalette(colourCount)) +
theme(legend.position="right")
雖然我們解決了顏色不足的問題,但其他有趣的事情發生了:雖然所有的柱子都回來了並且塗上了不同顏色,但是我們也失去了顏色圖例。我故意添加主題(legend.position = ...)來展示這個事實:盡管有明確的位置請求,但圖例不再是圖形的一部分。
差異:fill參數移動到柱狀圖aes函數之外 - 這有效地從ggplot的美學數據集中刪除了fill信息。因此,legend沒有應用到任何東西上。
要修復它,請將fill放回到aes中並使用scale_fill_manual()定義自定義調色板:
ggplot(mtcars) +
geom_bar(aes(factor(hp), fill=factor(hp))) +
scale_fill_manual(values = getPalette(colourCount))
在有大量柱子的柱狀圖中另一個可能的問題是legend的安放。用 theme 和 guides 來調整legend的位置和布局:
ggplot(mtcars) +
geom_bar(aes(factor(hp), fill=factor(hp))) +
scale_fill_manual(values = getPalette(colourCount)) +
theme(legend.position="bottom") +
guides(fill=guide_legend(nrow=2))
最后,在同一個例子中使用不同庫調色板的調色板構造函數:
ggplot(mtcars) +
geom_bar(aes(factor(hp), fill=factor(hp))) +
scale_fill_manual(values = colorRampPalette(brewer.pal(12, "Accent"))(colourCount)) +
theme(legend.position="bottom") +
guides(fill=guide_legend(nrow=2))