首页 文章

使geom_text颜色比geom_point颜色更暗

提问于
浏览
4

我用值标记散点图 . 为了使其可读,我希望文本颜色比点更暗(绿色点会有一个更深的绿色标签):

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)

我可以仅将其应用于文本吗?

2 回答

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

相关问题