Reputation: 703
I'm trying to create a new theme in ggplot2 for plotting political parties for my country, I want to set the color for some and other like random_party_1 y random_party_2 set a random color.
data <- data.frame(party = c('FA','PN', 'random_party1','random_party2', 'FA','PN', 'random_party1','random_party2'),
year = c(2010, 2010, 2010, 2010, 2008, 2008, 2008, 2008),
value = c(50, 20, 30, 10, 50, 50, NA, NA),
color = c('#013197','#B0C2D3','assign_random_color1','assign_random_color2','#013197','#B0C2D3','assign_random_color','assign_random_color'))
Then I want to use this as a fill or color argument but I don't know how to implement it without declaring it manually like because it's going to depend on the data of each year:
cols <- c("FA" = "#013197", "PN" = "#B0C2D3", "random_party1" = "assign_random_color1", "random_party2" = "assign_random_color2")
p + scale_colour_manual(values = cols)
Upvotes: 0
Views: 229
Reputation: 174586
I think the best way to achieve this is via a custom function:
colorize <- function(vec)
{
levs <- if(is.factor(vec)) levels(vec) else levels(factor(vec))
predefined <- c("FA", "PN")
pal <- c('#013197','#B0C2D3')
pal <- pal[match(levs, predefined)]
blanks <- which(is.na(pal))
pal[blanks] <- sample(colours(100), length(blanks))
pal
}
So suppose we set up your plot like this:
p <- ggplot(data, aes(factor(year), value, fill = party)) + geom_col(position = "dodge")
Then we can run our code once to get fixed colors for the predefined parties and random colors for the unassigned parties:
p + scale_fill_manual(values = colorize(data$party))
And we can see only the random parties' colors change if we run exactly the same code again:
p + scale_fill_manual(values = colorize(data$party))
Created on 2020-06-11 by the reprex package (v0.3.0)
Upvotes: 1