本文介绍了ggplot2:使用长因子名称将颜色固定为因子水平的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用ggplot2创建多个图形,并希望将固定的颜色分配给不同的组.为此,我正在使用问题 ggplot2:将颜色固定为因子水平 alistaire 提供.

I am creating several figures with ggplot2 and want to assign fixed colors to different groups. To do so, I am using the approach shown in question ggplot2: Fix colors to factor levels as provided by alistaire.

也就是说,我定义了自己的自定义比例

That is, I defined my own custom scale as follows

library(ggplot2)

scale_fill_ind <- function(...){
    ggplot2:::manual_scale(
        'fill', 
        values = setNames(c('green', 'blue', 'red', 'orange'), LETTERS[1:4]), 
        ...
    )
}

df1 <- data.frame(Value = c(40, 20, 10, 60), 
                  Type = c("A", "B", "C", "D"))

ggplot(df1, aes(x = Type, y = Value, fill = Type)) + 
    geom_col() + 
    scale_fill_ind()

df2 <- data.frame(Value = c(40, 20, 60), 
                  Type = c("A", "B", "D"))

ggplot(df2, aes(x = Type, y = Value, fill = Type)) + 
    geom_col() + 
    scale_fill_ind()

但是,在我自己的代码中,因子名称比"A","B",...长得多,因此我必须使用 str_wrap()在图例中强制"换行,每行最多25个字符.

However, in my own code, the factor names are significantly longer than just "A", "B",..., so that I have to "force" a linebreak in the legend with str_wrap() with a maximum of 25 characters per line.

但是,这避免了将颜色分配给具有换行符的我的因素.如果我缩短因子名称,则该方法效果很好.您有什么主意,如何为长"因子名称分配固定的颜色,以使上述方法可行?

This, however, avoids the colors to be assigned to my factors that have a linebreak. If I shorten the factor names, the approach works well. Do you have any idea, how I can assign fixed colors to my "long" factors names such that the approach above works?

非常感谢!

推荐答案

作为解决方法,您可以使用 paste :

As a workaround you could use paste:

library(ggplot2)

list_of_factors <- list(paste("Aaljdfgneopghpihj", "wgwgvldjnfgpwghiwg", sep = "\n"),
                     paste("Baodjfwapigaafgja", "3jgamdgvaksmngvaksn", sep = "\n"),
                     paste("Cskndvlsnvljengwlan", "kgaksnbvalsknbsfblskn", sep = "\n"),
                     paste("Dafsnjljbipenbvmdsvs", "mvslkbndfbkndfb", sep = "\n")) 

scale_fill_ind <- function(...){
  ggplot2:::manual_scale(
    'fill', 
    values = setNames(c('green', 'blue', 'red', 'orange'), list_of_factors), 
    ...
  )
}

df1 <- data.frame(Value = c(40, 20, 10, 60), 
                  Type = c(paste("Aaljdfgneopghpihj", "wgwgvldjnfgpwghiwg", sep = "\n"),
                           paste("Baodjfwapigaafgja", "3jgamdgvaksmngvaksn", sep = "\n"),
                           paste("Cskndvlsnvljengwlan", "kgaksnbvalsknbsfblskn", sep = "\n"),
                           paste("Dafsnjljbipenbvmdsvs", "mvslkbndfbkndfb", sep = "\n")))

ggplot(df1, aes(x = Type, y = Value, fill = Type)) + 
  geom_col() + 
  scale_fill_ind()

这篇关于ggplot2:使用长因子名称将颜色固定为因子水平的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-25 07:38