Reusing ggplot2 Colors

When you want to reuse ggplot2 default colors across plots.

random-code-snippets
ggplot2
visualization
Author

Robert M Flight

Published

December 21, 2021

If you are using {ggplot2} a lot in your code, and don’t want to bother with a custom color scheme (I mean, there are lots of good options), but you are also using non-ggplot2 type plots, and want to reuse the colors.

I frequently encounter this when I’m doing principal component analysis (PCA) combined with heatmaps plotted by {ComplexHeatmap}. I’ve colored sample groups in the PCA using {ggplot2} defaults, and now I want those same colors in the {ComplexHeatmap} row or column annotations.

The trick to this is extracting the palette from the color definition you want. For example, very commonly (in biology at least) we might have 2 classes of samples, cases and controls. So we need 2 colors.

When we generated the {ggplot2} plot, we would do something like this:

ggplot(data_frame, aes(x = var1, y = var2, color = groups))

To generate the matching colors for something else, we can do:

g_colors = scale_color_discrete()$palette(2)

Reuse

Citation

BibTeX citation:
@online{mflight2021,
  author = {Robert M Flight},
  title = {Reusing Ggplot2 {Colors}},
  date = {2021-12-21},
  url = {https://rmflight.github.io/posts/2021-12-21-reusing-ggplot2-colors},
  langid = {en}
}
For attribution, please cite this work as:
Robert M Flight. 2021. “Reusing Ggplot2 Colors.” December 21, 2021. https://rmflight.github.io/posts/2021-12-21-reusing-ggplot2-colors.