使geom_text颜色比geom_point颜色更暗
问题描述:
我使用值标记散点图。为了使其可读,我想文字颜色比点暗(绿点会有一个深绿色标签):使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)
我可以将它仅应用于文本吗?
答
你可以试试:
# 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)
答
定义颜色分:
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
这也是一个非常好的答案 - 谢谢 –
一个简单的黑客是改变'geom_point(阿尔法= 0.5)',这将使点显示“轻”,但它不是改变亮度相同,我觉得 – adibender
这是一个很好速战速决 - 谢谢。我不得不添加'geom_point(alpha = 0.5,shape = 16)'来防止该点出现黑色边框。 –