SkillAgentSearch skills...

Pubtheme

`ggplot` and `plotly` themes for creating publication quality visualizations for web and mobile.

Install / Use

/learn @bmacGTPM/Pubtheme
About this skill

Quality Score

0/100

Supported Platforms

Universal

README

<!-- README.md is generated from README.Rmd. Please edit that file -->

pubtheme

<!-- badges: start --> <!-- badges: end -->

The package pubtheme contains a ggplot theme theme_pub for creating data journalism-style data visualizations with color palettes and formatting similar to those used by media organizations like BBC, NY Times, and ESPN. Several templates for scatter plot, line plots, etc., are provided below for easy copying/pasting. A helpful function pub can be used to reduce then amount of code that needs to be typed when the user is comfortable with the default settings.

Organization-specific color palettes and logos can be used as well via the package orgthemes. See https://github.com/bmacGTPM/orgthemes.

Installation

If you don’t have the package devtools, install it using install.packages('devtools'). If you have devtools, you can install the GitHub version of pubtheme with:

devtools::install_github("bmacGTPM/pubtheme")

If you get an error about download method, try changing this option before installing.

options(download.file.method = 'libcurl')

Load the package using

library(pubtheme)

as usual. The theme will change some of your ggplot defaults the first time you use it. To change them back, restart R, or use

restore.ggplot.defaults()

at any time. It is recommended that you update your version of tidyverse and especially ggplot2 to use this package.

Scatter plot

dg = mtcars %>% 
  select(wt, mpg, cyl) %>%
  mutate(Cylinders = as.factor(cyl)) %>%
  rename(MPG = mpg)

title = "Title in Upper Lower" 
g = ggplot(dg, 
           aes(x     = wt, 
               y     = MPG, 
               color = Cylinders, 
               size  = MPG)) +
  geom_point() +
  labs(title    = title,
       subtitle = 'Optional Subtitle In Upper Lower',
       caption  = "Optional caption with more info, X handle, or shameless promotion of pubtheme",
       x = 'Horizontal Axis Label in Upper Lower',
       y = 'Vertical Axis Label in Upper Lower') +
  scale_x_continuous(limits = c(0, 6), 
                     breaks = c(0, 3, 6), 
                     oob    = squish, 
                     labels = comma) +
  scale_y_continuous(limits = c(0,40), 
                     breaks = c(0,20,40), 
                     oob    = squish, 
                     labels = comma) +
  scale_size(range = c(2, 6)) +
  coord_cartesian(clip   = 'off', 
                  expand = F) +
  theme_pub(type = 'scatter') 
print(g)

## Save to a file using base_size = 36
gg = g +
  scale_size(range = c(6, 18)) +
  theme_pub(type = 'scatter', 
            base_size = 36)

ggsave(filename = paste0("img/", gsub("%", " Perc", title), ".jpg"), 
       plot   = gg,
       width  = 20,   ## do not change
       height = 20,   ## can change from 20 if desired
       units  = 'in', ## do not change
       dpi    = 72)   ## do not change

g.scatter = g ## save for later
<img src="man/figures/README-scatter.old-1.png" style="display: block; margin: auto;" />

You must have a subfolder called img in order for the ggsave chunk above to work.

Note that the default is base_size = 12, which works well when viewing the image in RStudio. Use ggsave and base_size = 36 when saving an image instead of exporting from the RStudio viewer. Do not adjust the width = 20 in ggsave.

Do not change width = 20, units = 'in', or dpi = 72. Height can be adjusted if desired. A square image is often preferred, so when in doubt, keep height at 20.

Upper Lower means First letter of each word is capitalized. The option expand = FALSE removes the default padding. The option breaks=c(0, 3, 6) sets 3 lines at left, middle, and right. You can certainly add lines if there is a reason to, but when in doubt you can stick with just 3 lines (left/middle/right) only. Similarly, for the y-axis, top/middle/bottom only.

You’ll notice a scale_size(range = c(6, 18) when preparing the plot to be saved. If you are using size inside aes(), you’ll need that change the scale, otherwise the points will be too small.

pub function

We explicitly specified the scale* and coord_cartesian above. To use the default settings in pubtheme, you can save a lot of typing by using the function pub, which applies theme_pub and also automatically adds scale* and coord* similar to above. The function also aligns the legend with the left side of the title and subtitle.

title = "Title in Upper Lower" 
g = ggplot(dg, 
           aes(x     = wt, 
               y     = MPG, 
               color = Cylinders, 
               size  = MPG)) +
  geom_point() +
  labs(title    = title,
       subtitle = 'Optional Subtitle In Upper Lower',
       caption  = "Optional caption giving more info, X handle, or shameless promotion of pubtheme",
       x = 'Horizontal Axis Label in Upper Lower',
       y = 'Vertical Axis Label in Upper Lower')

g %>% 
  pub(xlim = c(0, 6),
      ylim = c(0, 40))

## Save to a file using base_size = 36
gg = g %>% 
  pub(xlim = c(0, 6), 
      ylim = c(0, 40), 
      base_size = 36)

ggsave(filename = paste0("img/", 
                         gsub("%", " Perc", title), 
                         ".jpg"), 
       plot   = gg,
       width  = 20,   ## do not change
       height = 20,   ## can change from 20 if desired
       units  = 'in', ## do not change
       dpi    = 72)   ## do not change
<img src="man/figures/README-scatter-1.png" style="display: block; margin: auto;" />

To save to a file, we again need base_size = 36. We simply copy and paste the pub code and add base_size = 36.

Correlation plot

Let’s make a correlation plot in the look of pubtheme. Since corrplot gives a corrplot object, pub can’t be used with it, so we have to make a correlation plot from scratch using geom_tile.

## choose order of variables
cols = sort(unique(colnames(mtcars)))

corr <- round(cor(mtcars[,cols]), 2)
head(corr,2)
#>        am carb   cyl  disp  drat gear    hp   mpg  qsec    vs    wt
#> am   1.00 0.06 -0.52 -0.59  0.71 0.79 -0.24  0.60 -0.23  0.17 -0.69
#> carb 0.06 1.00  0.53  0.39 -0.09 0.27  0.75 -0.55 -0.66 -0.57  0.43

dg = corr %>%
  as.data.frame() %>%
  
  ## longer format
  rownames_to_column(var = 'x') %>%
  pivot_longer(cols      = -x, 
               names_to  = 'y', 
               values_to = 'value') %>%
  
  ## order them however you'd like
  mutate(x = factor(x, levels = rev(sort(unique(x)))), 
         y = factor(y, levels = sort(unique(y))))

title = "Title in Upper Lower"
g = ggplot(dg) + 
  geom_tile(aes(x    = x, 
                y    = y, 
                fill = value),
            linewidth   = 0.4, 
            show.legend = T, 
            color       = pubdarkgray) +
  scale_fill_gradientn(colors = c('red4', 
                                  pubred, 
                                  publightred, 
                                  'white', ## or 'pubbackgray'
                                  publightblue, 
                                  pubblue, 
                                  'navy'),
                       na.value = pubmediumgray, ## same color as below
                       oob      = squish,
                       breaks   = c(-1, 0, 1),
                       limits   = c(-1,    1)) +

  labs(title    = title,
       subtitle = 'Optional Subtitle In Upper Lower',
       caption  = "Optional caption giving more info, X handle, or shameless promotion of pubtheme",
       x    = 'Day (Optional Axis Label in Upper Lower)', 
       y    = NULL, ## Optional
       fill = 'Value') 

g %>% 
  pub(type    = 'grid') + 
  theme(axis.text.x.top = element_text(angle = 90, 
                                   hjust = 0, 
                                   vjust = 0.3))

gg = g %>%
  pub(type      = 'grid', 
      base_size = 36)

ggsave(filename = paste0("img/", gsub("%", " Perc", title), ".jpg"), 
       plot   = gg,
       width  = 20,   ## do not change
       height = 24,   ## can change from 20 if desired. We use 12 here to make the tiles square
       units  = 'in', ## do not change
       dpi    = 72)   ## do not change
<img src="man/figures/README-corrplot-1.png" style="display: block; margin: auto;" />

Adding rectangles around clusters, as is often done in corrplot.


# ## note that the function corrRect.hclust is used there
# corrplot::corrplot
# 
# ## note that this converts corr to a distance matrix, and then uses cutree to get the clusters
# corrplot::corrRect.hclust

corr = cor(mtcars)
ds = as.dist(1-corr)
dh = hclust(ds)
hc = cutree(dh, k = 4)

dr = data.frame(order = dh$order,
                cluster = hc) %>%
  mutate(cluster = factor(cluster, 
                          levels = c(1,3,4,2))) %>% ## this order looks better
  arrange(cluster, order) %>%
  mutate(x = 1:n(),
         y = n():1) ## gotta reverse the order


dg = corr %>%
  as.data.frame() %>%
  
  ## longer format
  rownames_to_column(var = 'x') %>%
  pivot_longer(cols      = -x, 
               names_to  = 'y', 
               values_to = 'value') %>%
  
  ## order them the same way as dr
  mutate(x = factor(x, levels =     rownames(dr)),
         y = factor(y, levels = rev(rownames(dr))))

polys = dr %>%
  group_by(cluster) %>%
  summarise(xmin = min(x),
            xmax = max(x),
            ymin = min(y),
            ymax = max(y)) %>%
  mutate(xmin = xmin - 0.5,
         xmax = xmax + 0.5,
         ymin = ymin - 0.5,
         ymax = ymax + 0.5, 
         linewidth = 1.5)

title = "Title in Upper Lower"
g = ggplot(dg) + 
  
  ## Tiles
  geom_tile(aes(x    = x, 
                y    = y, 
                fill = value),
            linewidth   = 0.4, 
            show.legend = T, 
            color       = pubdarkgray) +
  
  ## Rectangles
  geom_rect(data = polys,
            aes(xmin = xmin,
                xmax = xmax,
                ymin = ymin,
                ymax = ymax,
                gro
View on GitHub
GitHub Stars11
CategoryDevelopment
Updated3mo ago
Forks0

Languages

R

Security Score

72/100

Audited on Dec 16, 2025

No findings