你可以試試:
# specify your colour
COL <- c("red", "blue", "green")
p1 <- ggplot(iris, aes(Sepal.Length, Sepal.Width, col = Species))+
geom_point()
p1 <- p1 + scale_colour_manual(values = COL)
現在變暗使用col2rgb
和rgb
(source)你的顏色或其他approach
COL2 <- col2rgb(COL)
COL2 <- COL2/2 # you can use of course other values than 2. Higher values the darker the output.
COL2 <- rgb(t(COL2), maxColorValue=255)
情節的標籤。
p1 + geom_text(aes(label = Sepal.Length), col=factor(iris$Species, labels=COL2), size = 2, position = position_dodge(width = 0.2))
爲了更好地瀏覽我推薦使用geom_text_repel
。值得注意的是,你必須使用as.character
。
require(ggrepel)
p1 + geom_text_repel(aes(label = Sepal.Length), size = 2, col= as.character(factor(iris$Species, labels=COL2)))
如果你不想在指定開始時的顏色,你也可以使用原始ggplot顏色提取:
g <- ggplot_build(p1)
COL <- unlist(unique(g$data[[1]]["colour"]))
然後你使用上面的代碼較暗的文本顏色或將所有內容組合在一個較暗的功能中:
p1 <- ggplot(iris, aes(Sepal.Length, Sepal.Width, col = Species))+
geom_point()
# function
darken <- function(Plot, factor=1.4){
g <- ggplot_build(Plot)
color <- unlist((g$data[[1]]["colour"]))
col <- col2rgb(color)
col <- col/factor
col <- rgb(t(col), maxColorValue=255)
col
}
# basic text
p1 + geom_text(aes(label = Sepal.Length), col=darken(p1, 2), size = 2, position = position_dodge(width = 0.2))
# repel text
p1 + geom_text_repel(aes(label = Sepal.Length), col= darken(p1, 2), size = 2)
一個簡單的黑客是改變'geom_point(阿爾法= 0.5)',這將使點顯示「輕」,但它不是改變亮度相同,我覺得 – adibender
這是一個很好速戰速決 - 謝謝。我不得不添加'geom_point(alpha = 0.5,shape = 16)'來防止該點出現黑色邊框。 –