2016-08-01 89 views
4

我使用值標記散點圖。爲了使其可讀,我想文字顏色比點暗(綠點會有一個深綠色標籤):使geom_text顏色比geom_point顏色更暗

p1 <- ggplot(iris, aes(Sepal.Length, Sepal.Width, col = Species))+ 
    geom_point()+ 
    geom_text(aes(label = Sepal.Length), size = 2, position = position_dodge(width = 0.2)) 

我可以使用scale_colour_discrete創造我想要的效果,但它適用於兩點和文字。

p1 + scale_colour_discrete(l = 50) 

我可以將它僅應用於文本嗎?

+1

一個簡單的黑客是改變'geom_point(阿爾法= 0.5)',這將使點顯示「輕」,但它不是改變亮度相同,我覺得 – adibender

+0

這是一個很好速戰速決 - 謝謝。我不得不添加'geom_point(alpha = 0.5,shape = 16)'來防止該點出現黑色邊框。 –

回答

1

你可以試試:

# 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) 

現在變暗使用col2rgbrgbsource)你的顏色或其他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))) 

enter image description here

如果你不想在指定開始時的顏色,你也可以使用原始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) 
1

定義顏色分:

n <- length(levels(iris$Species)) 
cols_points <- hcl(h = seq(15, 375, length = n + 1), l = 65, c = 100)[1:n] 

劇情點像你一樣在初期,手動設置顏色:

p1 <- ggplot(iris, aes(Sepal.Length, Sepal.Width, colour = Species)) + geom_point() + scale_colour_manual(values = cols_points) 

取出相同顏色時使用的情節,但改變色調定義文字顏色( L,可以調整到你有多黑想要它):

cols_text <- hcl(h = seq(15, 375, length = n + 1), l = 30, c = 100)[1:n] 

iris_cols <- ifelse(iris$Species == "setosa", cols_text[1], 
       ifelse(iris$Species == "versicolor", cols_text[2], cols_text[3])) 

情節與文本註釋(我加了小y的偏移,使文本和點不重疊):

p1 + annotate("text", x = iris$Sepal.Length, y = iris$Sepal.Width + 0.05, label = iris$Sepal.Length, color = iris_cols, size = 2) 
+0

這也是一個非常好的答案 - 謝謝 –