Search code examples
rggplot2colorsvisreg

Change Color by Group with visreg and ggplot


After running a logistic regression with a binary predictor, when I try to plot the results using visreg and ggplot the legend indicates that the colors have been changed by group but they don't change in the graph.

Here is an illustration of the problem using the mtcars data.

data(mtcars)
head(mtcars, 10)

The only two binary variables are the vs and am, but they need to be converted from numeric the factor for this illustration to work.

mtcars$vs <- as.factor(mtcars$vs)
mtcars$am <- as.factor(mtcars$am)

Run the model.

logit1 <- glm(vs ~ am, data = mtcars, family = "binomial")

Now try to plot the results using visreg as well as additional ggplot functions to customize the colors and labels.

visreg(logit1, "am", scale = "response", gg = TRUE, rug = FALSE, by = "am", overlay=TRUE) + 
  scale_color_manual(values=c("#1b9e77", "#d95f02"), 
                     breaks=c(0, 1), 
                     labels=c("Zeros", "Ones"))

I would for both the line and the shaded area should be orange (#d95f02) for the am = 1 group and both the line and the shaded area to be green (#1b9e77) for the am = 0 group. As you can see, that is not what the code produces. enter image description here


Solution

  • There's no functionality in visreg to enable you to do something like this right now. You can certainly change colors with, for example:

    visreg(logit1, "am", scale = "response", gg = TRUE, rug = FALSE, by = "am", overlay=TRUE,
           fill.par=list(fill="#1b9e77"), line.par=list(col='#d95f02'))
    

    But what you're describing is constructing an entirely different plot: one in which values of am are mapped to different colors. This would involve a completely different aes object that the plot is built upon. Unless there's some amazing ggplot2 trick out there that I am not aware of, there is no way to do this without rebuilding the plot from scratch.