The R versus Python debate is a favorite among data scientists. When it comes to data visualization, however, yours truly has a very clear preference: ggplot2 in R all the way.

Ease of data handling and formatting aside, ggplot2 shines in its customizability. The defaults look great, albeit very distinct, but with a bit of planning you can totally transform visualizations to fit any imaginable aesthetic. In this article I’ll walk through how to create a custom ggplot2 theme that can be applied to your graphs.

Open up a new R script that will contain your customizations. You’ll run this script before building any visualizations in order to make your settings available. You can package it up into a library, too, though that’s not strictly necessary.

Make sure to load up the necessary libraries. There’s nothing surprising here, just make sure ggplot and scales are loaded in before you do anything else.

library("ggplot2")
library("scales")

New font, new you. Right? There are several options for using a custom font in your graphs.

The first option involves using the fonts that are already on your machine. To access them, load the extrafont library and import all fonts to R. Warning: This is slow. Once you’ve run font_import(), comment it out and leave it alone. If you’re not sure what fonts are possible, use system_fonts() to see a list.

library("extrafont")
font_import() # only run this once then comment out. It's slow!
extrafont::loadfonts()
library("systemfonts")
system_fonts() # shows you available fonts

The second option is to add in a Google font. The showtext library will let you import a font from the Google font page using the font_add_google() function. In this example, I’m importing the Reenie Beanie font for a fun handwriting effect.

library("showtext")
## Loading Google fonts (https://fonts.google.com/)
graphFont = "Reenie Beanie"
font_add_google(graphFont)

Under normal circumstances you might use the theme() argument to make small changes to the default settings. Because ggplot2 is layered, adding +theme() to the end of a visualization will override any preceding settings.

We can take advantage of this behavior by defining a bespoke theme that can be added at the end of any visualization. This means you could even go back to old work and apply your new theme to achieve a consistent portfolio. In this example, I’ve defined a straightforward theme that makes all the text black, specifies various background fills, and sets the font. Running theme

Continue reading: https://towardsdatascience.com/designing-custom-ggplot2-themes-65fb4b86d925?source=rss—-7f60cf5620c9—4

Source: towardsdatascience.com