Reputation: 11
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()
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?
Thank you very much!
Upvotes: 1
Views: 255
Reputation: 26690
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()
Upvotes: 0