README.md

ggfocus

Introduction

Many times during data analysis, one may want to visualize data for a specific subgroup of observations. While ggplot is great for data visualization in general, constructing graphics that focus on those subgroups may need very troublesome manipulation of data and graphical scales (for example colors), i.e. setting low alpha for unimportant observations, coloring things in a way that highlights the focus subgroup, etc.

ggfocus allows you to build graphics that focus on those specific subgroups by doing the scale manipulation automatically while keeping all the flexibility from ggplot. The idea behind this approach is from this issue from tidyverse/ggplot2.

Installing ggfocus

The package is not available in CRAN (yet), but you can install it from github with devtools.

devtools::install_github("Freguglia/ggfocus")

Usage

ggfocus implements the ggfocus() function.

ggfocus(p, var, focus_levels, focus_aes = c("color", "alpha"),
  color_focus = NULL, color_other = "black", alpha_focus = 1,
  alpha_other = 0.05)

Examples

Using the gapminder dataset, first we create our ggplot

library(ggplot2)
library(gapminder)
p <- ggplot(gapminder, aes(x=log(gdpPercap), y=lifeExp, group=country)) + geom_line()
p

Now we can use ggfocus() to highlight European countries only.

library(ggfocus)
ggfocus(p, continent, "Europe")

We can also highlight countries

ggfocus(p, country, c("Brazil","Argentina"), color_focus = c("Green","Blue"))

Interaction with other extensions

Because ggfocus() retuns a modified ggplot object, other ggplot extensions can used with it, for example, gganimate.

library(gganimate)
p <- ggplot(gapminder, aes(x=log(gdpPercap), y=lifeExp, size=pop, frame=year)) + geom_point()
focus_p <- ggfocus(p,country,c("Brazil","Argentina"), color_focus = c("Green","Blue"))
gganimate(focus_p,interval=.2)

Using ggfocus with ggmaps

library(ggmap)
library(maps)

wm <- map_data("world")
p <- ggplot(wm, aes(x=long, y = lat, group = group)) + geom_polygon(color="black") + theme_void()
ggfocus(p, region, c("Brazil","India","Italy","Canada"),focus_aes = c("fill","alpha"),
        color_focus = "blue", alpha_other = 0.15) + guides(fill=FALSE)



Try the ggfocus package in your browser

Any scripts or data that you put into this service are public.

ggfocus documentation built on May 29, 2018, 5:04 p.m.