{"id":16896163,"url":"https://github.com/teunbrand/ggplot_tricks","last_synced_at":"2025-04-09T09:07:45.835Z","repository":{"id":65803809,"uuid":"590648322","full_name":"teunbrand/ggplot_tricks","owner":"teunbrand","description":"Here, I collect some tricks I've learned about the {ggplot2} R package","archived":false,"fork":false,"pushed_at":"2024-02-27T17:14:45.000Z","size":1031,"stargazers_count":294,"open_issues_count":0,"forks_count":13,"subscribers_count":11,"default_branch":"main","last_synced_at":"2025-04-02T06:08:32.223Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/teunbrand.png","metadata":{"files":{"readme":"README.Rmd","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null}},"created_at":"2023-01-18T22:05:06.000Z","updated_at":"2025-03-22T08:13:27.000Z","dependencies_parsed_at":"2023-02-18T23:15:21.664Z","dependency_job_id":null,"html_url":"https://github.com/teunbrand/ggplot_tricks","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/teunbrand%2Fggplot_tricks","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/teunbrand%2Fggplot_tricks/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/teunbrand%2Fggplot_tricks/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/teunbrand%2Fggplot_tricks/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/teunbrand","download_url":"https://codeload.github.com/teunbrand/ggplot_tricks/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248008630,"owners_count":21032556,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-10-13T17:28:42.722Z","updated_at":"2025-04-09T09:07:45.805Z","avatar_url":"https://github.com/teunbrand.png","language":null,"funding_links":[],"categories":["Miscellaneous"],"sub_categories":[],"readme":"---\noutput: github_document\n---\n\n\u003c!-- README.md is generated from README.Rmd. Please edit that file --\u003e\n\n```{r, include = FALSE}\nknitr::opts_chunk$set(\n  collapse = TRUE,\n  comment = \"#\u003e\",\n  fig.path  = \"man/figures/README-\",\n  fig.align = \"center\",\n  out.width = \"80%\",\n  dev       = \"ragg_png\",\n  dpi       = 132\n)\n```\n\n# ggplot tricks\n\n\u003c!-- badges: start --\u003e\n\u003c!-- badges: end --\u003e\n\nThe goal of this repository is to keep track of some neat [ggplot2](https://ggplot2.tidyverse.org/) tricks I've learned. This assumes you've familiarised yourself with the basics of ggplot2 and can construct some nice plots of your own. If not, please peruse the [book](https://ggplot2-book.org/) at your leasure.\n\nI'm not incredibly adapt in gloriously typesetting plots and expertly finetuning themes and colour palettes, so you'd have to forgive me. The `mpg` dataset is very versatile for plotting, so you'll be seeing a lot of that as you read on. Extension packages are great, and I've dabbled myself, but I'll try to limit myself to vanilla ggplot2 tricks here.\n\nFor now, this will be mostly a README-only bag of tricks, but I may decide later to put them into separate groups in other files.\n\n## Table of contents\n\n1. [Start-up](#let's-begin)\n1. [Splicing aesthetics](#splicing-aesthetics)\n    1. [Colour-fill relations](#relating-colour-and-fill)\n    1. [Text contrast](#text-contrast)\n1. [Half-geoms](#half-geoms)\n    1. [Half-boxplots](#half-boxplots)\n    1. [Half-errorbars](#half-errorbars)\n    1. [Half-violin](#half-violin)\n    1. [Combining](#combining)\n1. [Midpoints in diverging scales](#setting-midpoints-in-divergent-scales)\n1. [Labels as text](#labels-as-text)\n    1. [Labelling points](#labelling-points)\n    1. (Outdated)[Facetted tags](#facetted-tags)\n1. [Recycling plots](#recycling-plots)\n    1. [Functions](#functions)\n    1. [Skeletons](#skeletons)\n    1. [Ribcage](#ribcage)\n\n## Let's begin\n\nBy loading the library and setting a plotting theme. \nThe first trick here is to use `theme_set()` to set a theme for *all* your plots throughout a document. If you find yourself setting a very verbose theme for every plot, here is the place where you set all your common settings. Then never write a novel of theme elements ever again[^theme]!\n\n[^theme]: Well, you need to do it once at the start of your document. But then never again! Except in your next document. Just write a `plot_defaults.R` script and `source()` that from your document. Copy-paste that script for every project. Then, truly, *never* again :heart:.\n\n```{r}\nlibrary(ggplot2)\nlibrary(scales)\n\ntheme_set(\n  # Pick a starting theme\n  theme_gray() +\n  # Add your favourite elements\n  theme(\n    axis.line        = element_line(),\n    panel.background = element_rect(fill = \"white\"),\n    panel.grid.major = element_line(\"grey95\", linewidth = 0.25),\n    legend.key       = element_rect(fill = NA) \n  )\n)\n```\n\n## Splicing aesthetics\n\nThe `?aes` documentation doesn't tell you this, but you can splice the `mapping` argument in ggplot2. \nWhat does that mean? \nWell it means that you can compose the `mapping` argument on the go with `!!!`. \nThis is especially nifty if you need to recycle aesthetics every once in a while.\n\n```{r splice_aes}\nmy_mapping \u003c- aes(x = foo, y = bar)\n\naes(colour = qux, !!!my_mapping)\n```\n\n### Relating colour and fill\n\nMy personal favourite use of this is to make the `fill` colour match the `colour` colour, but slightly lighter[^myfill]. \nWe'll use the delayed evaluation system for this, `after_scale()` in this case, which you'll see more of in the section following this one.\nI'll repeat this trick a couple of times throughout this document.\n\n[^myfill]: This is a lie. In reality, I use `aes(colour = after_scale(colorspace::darken(fill, 0.3)))` instead of lightening the fill. I didn't want this README to have a dependency on {colorspace} though.\n\n```{r, splice_colour}\nmy_fill \u003c- aes(fill = after_scale(alpha(colour, 0.3)))\n\nggplot(mpg, aes(displ, hwy)) +\n  geom_point(aes(colour = factor(cyl), !!!my_fill), shape = 21)\n```\n\n### Text contrast\n\nYou may find yourself in a situation wherein you're asked to make a heatmap of a small number of variables.\nTypically, sequential scales run from light to dark or vice versa, which makes text in a single colour hard to read.\nWe could devise a method to automatically write the text in white on a dark background, and black on a light background. The function below considers a lightness value for a colour, and returns either black or white depending on that lightness.\n\n```{r constrast}\ncontrast \u003c- function(colour) {\n  out   \u003c- rep(\"black\", length(colour))\n  light \u003c- farver::get_channel(colour, \"l\", space = \"hcl\")\n  out[light \u003c 50] \u003c- \"white\"\n  out\n}\n```\n\nNow, we can make an aesthetic to be spliced into a layer's `mapping` argument on demand.\n\n```{r autocontrast}\nautocontrast \u003c- aes(colour = after_scale(contrast(fill)))\n```\n\nLastly, we can test out our automatic contrast contraption. \nYou may notice that it adapts to the scale, so you wouldn't need to do a bunch of conditional formatting for this.\n\n```{r splice_contrast, fig.show='hold'}\ncors \u003c- cor(mtcars)\n\n# Melt matrix\ndf \u003c- data.frame(\n  col = colnames(cors)[as.vector(col(cors))],\n  row = rownames(cors)[as.vector(row(cors))],\n  value = as.vector(cors)\n)\n\n# Basic plot\np \u003c- ggplot(df, aes(row, col, fill = value)) +\n  geom_raster() +\n  geom_text(aes(label = round(value, 2), !!!autocontrast)) +\n  coord_equal()\n\np + scale_fill_viridis_c(direction =  1)\np + scale_fill_viridis_c(direction = -1)\n```\n\n## Half-geoms\n\nThere are some extensions that offer half-geom versions of things. Of the ones I know, [gghalves](https://erocoar.github.io/gghalves/) and the [see](https://easystats.github.io/see/) package offer some half-geoms.\n\nHere is how to abuse the [delayed evaluation system](https://ggplot2.tidyverse.org/reference/aes_eval.html) to make your own. This can come in handy if you're not willing to take on an extra dependency for just this feature.\n\n### Half-boxplots\n\nThe easy case is the boxplot. You can either set `xmin` or `xmax` to `after_scale(x)` to keep the right and left parts of a boxplot respectively. This still works fine with `position = \"dodge\"`.\n\n```{r half_boxplot}\n# A basic plot to reuse for examples\np \u003c- ggplot(mpg, aes(class, displ, colour = class, !!!my_fill)) +\n  guides(colour = \"none\", fill = \"none\") +\n  labs(y = \"Engine Displacement [L]\", x = \"Type of car\")\n\np + geom_boxplot(aes(xmin = after_scale(x)))\n```\n\n### Half-errorbars\n\nThe same thing that works for boxplots, also works for errorbars.\n\n```{r half_errorbar}\np + geom_errorbar(\n  stat = \"summary\",\n  fun.data = mean_se,\n  aes(xmin = after_scale(x))\n)\n```\n\n### Half-violin\n\nWe can once again do the same thing for violin plots, but the layer complains about not knowing about the `xmin` aesthetic. It does use that aesthetic, but only after the data has been setup, so it is not *intended* to be a user accessible aesthetic. We can silence the warning by updating the `xmin` default to `NULL`, which means it won't complain, but also doesn't use it if absent. \n\n```{r half_violin}\nupdate_geom_defaults(\"violin\", list(xmin = NULL))\n\np + geom_violin(aes(xmin = after_scale(x)))\n```\n\n### Combining\n\nNot left as an exercise for the reader this time, but I just wanted to show how it would work if you were to combine two halves and want them a little bit offset from one another. We'll abuse the errorbars to serve as staples for the boxplots.\n\n```{r combine_halves}\n# A small nudge offset\noffset \u003c- 0.025\n\n# We can pre-specify the mappings if we plan on recycling some\nright_nudge \u003c- aes(\n  xmin = after_scale(x), \n  x = stage(class, after_stat = x + offset)\n)\nleft_nudge  \u003c- aes(\n  xmax = after_scale(x),\n  x = stage(class, after_stat = x - offset)\n)\n\n# Combining\np +\n  geom_violin(right_nudge) +\n  geom_boxplot(left_nudge) +\n  geom_errorbar(left_nudge, stat = \"boxplot\", width = 0.3)\n```\n\n## Setting midpoints in divergent scales\n\nLet's say you have better colour intuition than I have, and three colours aren't enough for your divergent colour palette needs. A painpoint is that it is tricky to get the midpoint right if your limits aren't perfectly centered around it. Enter the `rescaler` argument in league with `scales::rescale_mid()`.\n\n```{r divergent_midpoint}\nmy_palette \u003c- c(\"dodgerblue\", \"deepskyblue\", \"white\", \"hotpink\", \"deeppink\")\n\np \u003c- ggplot(mpg, aes(displ, hwy, colour = cty - mean(cty))) +\n  geom_point() +\n  labs(\n    x = \"Engine displacement [L]\",\n    y = \"Highway miles per gallon\",\n    colour = \"Centered\\nvalue\"\n  )\n\np + \n  scale_colour_gradientn(\n    colours = my_palette, \n    rescaler = ~ rescale_mid(.x, mid = 0)\n  )\n```\n\nAn alternative is to simply center the limits on x. We can do that by providing a function to the scale's limits.\n\n```{r centered_midpoint}\np +\n  scale_colour_gradientn(\n    colours = my_palette, \n    limits = ~ c(-1, 1) * max(abs(.x))\n  )\n```\n\n\n## Labels as text\n\n### Labelling points\n\nYou can label points with `geom_text()`, but a potential problem is that the text and points overlap.\n\n```{r scatterplot_text_1}\nset.seed(0)\ndf \u003c- USArrests[sample(nrow(USArrests), 5), ]\ndf$state \u003c- rownames(df)\n\nq \u003c- ggplot(df, aes(Murder, Rape, label = state)) +\n  geom_point()\nq + geom_text()\n```\n\nThere are several typical solutions to this problem, and they all come with drawbacks:\n\n* The [{ggrepel}](https://ggrepel.slowkow.com/) package is wonderful for solving this problem. But if you try to keep your dependencies to a minimum, you might not want to depend on it.\n* You can set the `nudge_x` and `nudge_y` parameters. The issue here is that these are defined in data units, so spacing is unpredictable, and there is no way to have these depend on the original locations.\n* You can set the `hjust` and `vjust` aesthetics. It allows you to depend on the original locations, but these have no natural offsets.\n\nHere are options 2 and 3 in action:\n\n```{r scatterplot_text_2, fig.show='hold'}\nq + geom_text(nudge_x = 1, nudge_y = 1)\n\nq + geom_text(aes(\n  hjust = Murder \u003e mean(Murder),\n  vjust = Rape \u003e mean(Rape)\n))\n```\n\nYou might think: 'I can just multiply the justifications to get a wider offset', and you'd be right.\nHowever, because the justification depends on the size of text you might get unequal offsets. Notice in the plot below that 'North Dakota' is offset too munch in the y-direction and 'Rhode Island' in the x-direction.\n\n```{r scatterplot_text_3}\nq + geom_text(aes(\n  label = gsub(\"North Dakota\", \"North\\nDakota\", state),\n  hjust = ((Murder \u003e mean(Murder)) - 0.5) * 1.5 + 0.5,\n  vjust = ((Rape \u003e mean(Rape)) - 0.5) * 3 + 0.5\n))\n```\n\nThe nice thing of `geom_label()` is that you can turn off the label box and keep the text. That way, you can continue to use other useful stuff, like the `label.padding` setting, to give an absolute (data-independent) offset from the text to the label.\n\n```{r scatterplot_label}\nq + geom_label(\n  aes(\n    label = gsub(\" \", \"\\n\", state),\n    hjust = Murder \u003e mean(Murder),\n    vjust = Rape \u003e mean(Rape)\n  ),\n  label.padding = unit(5, \"pt\"),\n  label.size = NA, fill = NA\n)\n```\n\n### Facetted tags\n\nThis used to be a tip about putting facet tags in panels, which used to be complicated. With ggplot2 3.5.0, you no longer have to fiddle with setting infinite positions and tweaking the `hjust` or `vjust` parameters. You can now just use `x = I(0.95), y = I(0.95)` to place text in the upper-right corner. Open up the details to see the old tip.\n\n\u003cdetails\u003e\n\nPutting text annotations on facetted plots is a pain, because limits can vary on a per-panel basis, so it is very difficult to find the correct position. \nAn extension that explores alleviating this pain is the [tagger](https://github.com/eliocamp/tagger) extension, but we can do a similar thing in vanilla ggplot2.\n\nLuckily, there is a mechanic in ggplot2's position axes that let's `-Inf` and `Inf` be interpreted as the scale's minimum and maximum limit respectively[^oob]. \nYou can exploit this by choosing `x = Inf, y = Inf` to put the labels in a corner. \nYou can also use `-Inf` instead of `Inf` to place at the bottom instead of top, or left instead of right.\n\n[^oob]: Unless you self-sabotage your plots by setting `oob = scales::oob_censor_any` in the scale for example.\n\nWe need to match the `hjust`/`vjust` arguments to the side of the plot. \nFor `x/y = Inf`, they would need to be `hjust/vjust = 1`, and for `x/y = -Inf` they need to be `hjust/vjust = 0`.\n\n```{r facet_tag_text}\np + facet_wrap(~ class, scales = \"free\") +\n  geom_text(\n    # We only need 1 row per facet, so we deduplicate the facetting variable\n    data = ~ subset(.x, !duplicated(class)),\n    aes(x = Inf, y = Inf, label = LETTERS[seq_along(class)]),\n    hjust = 1, vjust = 1,\n    colour = \"black\"\n  )\n```\n\nUnfortunately, this places the text straight at the border of the panel, which may offend our sense of beauty. \nWe can get slightly fancier by using `geom_label()`, which lets us more precisely control the spacing between the text and the panel borders by setting the `label.padding` argument. \n\nMoreover, we can use `label.size = NA, fill = NA` to hide the textbox part of the geom. \nFor illustration purposes, we now place the tag at the top-left instead of top-right.\n\n```{r facet_tag_label}\np + facet_wrap(~ class, scales = \"free\") +\n  geom_label(\n    data = ~ subset(.x, !duplicated(class)),\n    aes(x = -Inf, y = Inf, label = LETTERS[seq_along(class)]),\n    hjust = 0, vjust = 1, label.size = NA, fill = NA,\n    label.padding = unit(5, \"pt\"),\n    colour = \"black\"\n  )\n```\n\n\u003c/details\u003e\n\n## Recycling plots\n\nLet's say we're tasked with making a bunch of similar plots, with different datasets and columns.\nFor example, we might want to make a series of barplots[^bar] with some specific pre-sets: we'd like the bars to touch the x-axis and not draw vertical gridlines.\n\n[^bar]: In your soul of souls, do you *really* want to make a bunch of barplots though?\n\n### Functions\n\nOne well-known way to make a bunch of similar plots is to wrap the plot construction into a function. \nThat way, you can use encode all the presets you want in your function.\n\nI case you might not know, there are various methods to [program with the `aes()` function](https://ggplot2.tidyverse.org/articles/ggplot2-in-packages.html#using-aes-and-vars-in-a-package-function), and using `{{ }}` (curly-curly) is one of the more flexible ways [^aes].\n\n[^aes]: The alternative is to use the `.data` pronoun, which can be `.data$var` if you want to lock in that column in advance, or `.data[[var]]` when `var` is passed as a character.\n\n```{r barplot_fun}\nbarplot_fun \u003c- function(data, x) {\n  ggplot(data, aes(x = {{ x }})) +\n    geom_bar(width = 0.618) +\n    scale_y_continuous(expand = c(0, 0, 0.05, 0)) +\n    theme(panel.grid.major.x = element_blank())\n}\n\nbarplot_fun(mpg, class)\n```\n\nOne drawback of this approach is that you lock-in any aesthetics in the function arguments. \nTo go around this, an even simpler way is to simply pass `...` directly to `aes()`.\n\n```{r barplot_fun_ellipsis}\nbarplot_fun \u003c- function(data, ...) {\n  ggplot(data, aes(...)) +\n    geom_bar(width = 0.618) +\n    scale_y_continuous(expand = c(0, 0, 0.1, 0)) +\n    theme(panel.grid.major.x = element_blank())\n}\n\nbarplot_fun(mpg, class, colour = factor(cyl), !!!my_fill)\n```\n\n\n### Skeletons\n\nAnother method of doing a very similar thing, is to use plot 'skeletons'. \nThe idea behind a skeleton is that you can build a plot, with or without any `data` argument, and add in the specifics later. \nThen, when you actually want to make a plot, you can use the `%+%` to fill in or replace the dataset, and `+ aes(...)` to set the relevant aesthetics.\n\n```{r, barplot_skelly}\nbarplot_skelly \u003c- ggplot() +\n  geom_bar(width = 0.618) +\n  scale_y_continuous(expand = c(0, 0, 0.1, 0)) +\n  theme(panel.grid.major.x = element_blank())\n\nmy_plot \u003c- barplot_skelly %+% mpg + \n  aes(class, colour = factor(cyl), !!!my_fill) \nmy_plot\n```\n\nOne neat thing about these skeletons is that even when you've already filled in the `data` and `mapping` arguments, you can just replace them again and again.\n\n```{r barplot_skelly_replace}\nmy_plot %+% mtcars + \n  aes(factor(carb), colour = factor(cyl), !!!my_fill)\n```\n\n### Ribcage[^cage]\n\n[^cage]: This bit was originally called 'partial skeleton', but as a ribcage is a part of a skeleton, this title sounded more evocative.\n\nThe idea here is to not skeletonise the entire plot, but just a frequently re-used set of parts. \nFor example, we might want to label our barplot, and pack together all the things that make up a labelled barplot. \nThe trick to this is to *not* add these components together with `+`, but simply put them in a `list()`. You can then `+` your list together with the main plot call.\n\n```{r ribcage, fig.show='hold'}\nlabelled_bars \u003c- list(\n  geom_bar(my_fill, width = 0.618),\n  geom_text(\n    stat = \"count\",\n    aes(y     = after_stat(count), \n        label = after_stat(count), \n        fill  = NULL, colour = NULL),\n    vjust = -1, show.legend = FALSE\n  ),\n  scale_y_continuous(expand = c(0, 0, 0.1, 0)),\n  theme(panel.grid.major.x = element_blank())\n)\n\nggplot(mpg, aes(class, colour = factor(cyl))) +\n  labelled_bars +\n  ggtitle(\"The `mpg` dataset\")\n\nggplot(mtcars, aes(factor(carb), colour = factor(cyl))) +\n  labelled_bars +\n  ggtitle(\"The `mtcars` dataset\")\n```\n\n  \u003cdetails style=\"margin-bottom:10px;\"\u003e\n  \u003csummary\u003e\n  Session info\n\u003c/summary\u003e\n\n```{r, echo = FALSE}\nsi \u003c- sessioninfo::session_info()\n\n# People don't need to see my file paths etc\nsi$platform$pandoc \u003c- gsub(\" @ C:/.*\", \"\", si$platform$pandoc)\nsi$packages$library \u003c- NULL\n\nprint(si)\n```\n\n\u003c/details\u003e\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fteunbrand%2Fggplot_tricks","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fteunbrand%2Fggplot_tricks","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fteunbrand%2Fggplot_tricks/lists"}