Reusing ggplot2 Colors

random-code-snippets ggplot2 visualization

When you want to reuse ggplot2 default colors across plots.

Robert M Flight true

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)


If you see mistakes or want to suggest changes, please create an issue on the source repository.


Text and figures are licensed under Creative Commons Attribution CC BY 4.0. Source code is available at, unless otherwise noted. The figures that have been reused from other sources don't fall under this license and can be recognized by a note in their caption: "Figure from ...".


For attribution, please cite this work as

Flight (2021, Dec. 21). Deciphering Life: One Bit at a Time: Reusing ggplot2 Colors. Retrieved from

BibTeX citation

  author = {Flight, Robert M},
  title = {Deciphering Life: One Bit at a Time: Reusing ggplot2 Colors},
  url = {},
  year = {2021}