Skip to content

Instantly share code, notes, and snippets.

fun_labels <- function(x) sprintf("<b>%s</b>", x)
ggplot() +
scale_x(breaks = c('a','b','c')) +
theme(axis.label = element_sticker(grob = fancyGrob, dictionary = fun_labels))
my_labels <- tibble(label = letters[1:3], grobs = I(lapply(1:3, fancyGrob)))
@thomasp85
thomasp85 / trim_model.R
Created October 24, 2017 07:26
Trim all unnecessary data from model objects
library(future)
trim_model <- function(model, predictor = predict, ..., ignore_warnings = TRUE) {
# Cache the correct output
true_pred <- predictor(model, ...)
# Treat prediction warnings as errors?
if (!ignore_warnings) {
old_ops <- options(warn = 2)
on.exit(options(old_ops))
}
@sfirke
sfirke / add_centered_title.R
Last active September 21, 2017 18:00
Center all of your ggplot2 titles over the whole plot using a function
library(ggplot2)
library(dplyr)
library(grid)
library(gridExtra)
add_centered_title <- function(p, text, font_size){
title.grob <- textGrob(
label = text,
gp = gpar(fontsize = font_size,
@jennybc
jennybc / noam.R
Last active June 26, 2019 15:20
Faking tidyr::drop_na(..., logic = "all")
library(tidyverse)
(df <- tibble(
x = c(1, NA, 3, NA),
y = c(1, NA, NA, 4),
z = 1:4
))
#> # A tibble: 4 × 3
#> x y z
#> <dbl> <dbl> <int>
#> 1 1 1 1
@baptiste
baptiste / ggguide.r
Last active October 10, 2017 19:19
what if ggplot guides were ggplots
library(ggplot2)
library(grid)
d <- data.frame(x=rnorm(50), y=rnorm(50), f1 = rep(gl(5,5), 2), f2 = gl(2, 25))
p <- ggplot(d, aes(x,y, group=interaction(f1,f2))) +
geom_line(aes(colour=f1, linetype=f2)) +
geom_point(aes(colour=f1, shape=f1))
@jimhester
jimhester / ternary.R
Last active November 9, 2021 19:17
Ternary operator in R
``` r
`?` <- function(x, y) {
y <- substitute(y)
if (!is.call(y) || !identical(as.symbol(":"), y[[1]])) stop("Invalid", call. = FALSE)
eval(call("if", x, y[[2]], y[[3]]))
}
T ? 1
#> Error: Invalid
@Myfanwy
Myfanwy / heythanks.r
Last active September 14, 2022 21:57
a ggplot2 thank you
# requires Megrim font: https://fonts.google.com/specimen/Megrim
if(FALSE) {
install.packages("extrafont")
extrafont::loadfonts()
}
library(ggplot2)
ggplot() +
scale_x_continuous(expand = c(0,0)) +
@noamross
noamross / gg_epi.R
Last active May 14, 2022 03:47
Animating vertices of a graph with gganimate and ggraph
library(tidyverse)
library(igraph)
library(ggraph)
library(gganimate)
library(ggforce)
#File at https://dl.dropbox.com/s/hxmsut19lelgw33/epinetwork.rds
episim <- readRDS("epinetwork.rds") # Saved is the simulation data and an adjacency matrix for the network
# Create an undirected graph from this matrix
ign <- graph_from_adjacency_matrix(episim$network > 0, "undirected")