A 'ggplot2' extension that provides tools for automatically focusing specific factor levels.
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.
The package is available on CRAN, but you can also install the latest version from github with devtools.
devtools::install_github("Freguglia/ggfocus") # Latest version install.packages("ggfocus") # CRAN version
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)
You can also use the usual
+ to add scales with the
family of function
scale_*_focus(). These two uses are equivalent,
read the vignette for more
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"))
Because ggfocus() retuns a modified ggplot object, other ggplot extensions can used with it, for example, ggmap.
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)
NEWS.mdfile to track changes to the package.