How to use functions to custom style ggplot

So I've got some data:

age,height,label

I'm using ggplot to create a regression line plus prediction interval for each label subset.
Works fine.
Now I want to control the fill, color and alpha of each subgraph. I thought what if I use a function for each type (color, fill and alpha) that gets the current label (group) and returns the correct parameter to set the fill,color and alpha in any custom way.
I can't seem to find the way to use something like within ggplot to call my functions.
Example:

my_colors <- function(current_group) {
switch(current_group,
A = "#f0f0f0",
B = "#ff0000",
C = "#00ff00",
"#0000ff"
)
}

ggplot(data = plottoplot, aes(x = age, y = height, group = label)) +
geom_line(aes(y=lwr)) +
geom_line(aes(y=upr)) +
geom_ribbon(aes(ymin = lwr, ymax = upr, fill = my_colors(group))) +
geom_smooth(method=lm, se=FALSE)
theme_minimal() #use default minimal theme for layout

So here I've got just one line trying to set the fill color

geom_ribbon(aes(ymin = lwr, ymax = upr, fill = my_colors(group))) +

And I want to do something like: fill = my_colors(current-group-value)

Is there a way to do this?

Thx!

Marco

scale_fill_manual

library(tidyverse)

cols <- c("setosa" = "#f0f0f0", 
          "versicolor" = "#ff0000",
          "virginica" = "#00ff00" )

ggplot(data=iris,
       mapping=aes(x=Petal.Length,y=Sepal.Length,fill=Species)) +
  scale_fill_manual(values = cols)+
  geom_smooth()
1 Like

Great! That works perfectly.
Thanks!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.