JavaScript Loaders

Showing posts with label plot. Show all posts
Showing posts with label plot. Show all posts

Saturday, April 16, 2016

Creating and Tweaking Bubble Chart with ggplot2

This article will take us step-by-step over incremental changes to produce a bubble chart using ggplot2 that looks like this:


Data and Setup

We'll encounter the plot above once again at the very end after explaining each step with code changes and observing intermediate plots. Without getting into details what it means (curios reader can find out here) the dataset behind is defined as:


It contains 2 data points and 4 attributes: three numerical Aster_experience, R_experience, and  coverage, and one categorical product. Remember that the data won't change a bit while the plot progression unfolds.

As-Is Scatterplot

The starting plot is simple scatterplot using coordinates x and y as Aster_experience, R_experience (line 3), point size as coverage, and point color as product (line 4) (this type of scatterplot has a special name - bubble chart):




Fixing Point Sizes

Immediate fix would be making the smaller point big enough to see it with the help of scale_size function and its range argument (line 3) (strange enough but sibling function scale_size_area doesn't have such argument) that specifies the minimum and maximum size of the plotting symbol after transformation1 :



Magic Quadrant: adding lines and customizing axises

Next refinement aims at the magic quadrant concept which fits this data well. In this case it's "R Experience" vs. "Aster Experience" and whether there is more or less of each. Achieving this effect involves fake axes using geom_hline and geom_vline (line 3), and customizing actual axes using scale (line 5-6) and theme functions (line 8-12):




Adding Text and Color to Points 

Typical for bubble charts its points get both colored and labeled, which also makes color bar legend obsolete. We use geom_text to label points (line 5) and scale_color_manual to assign new colors and remove color bar legend (line 11):



Customizing Legend

The next step happened to tackle the most advanced problem while working on the plot. The guide legend for size above looks rather awkward. Ideally, it matches the two points we have in both color and size. It turned out (and rightly so) that the function scale_size is responsible for its appearance (line 8). In particular, number of legend positions overrides argument breaks, and controling appearance including colors of the legend performed with guide_legend and override.aes:



Finishing Touch with Custom Theme

We finish cleaning the plot using package ggthemes and its theme_tufte function (line 10):




As promised, we finished exactly where we started.


1 Scale size (area or radius).↩

Friday, September 13, 2013

How to expand color palette with ggplot and RColorBrewer

Histograms and bar charts are almost always a part of data analysis presentation. If it is made with R ggplot package functions geom_histogram() or geom_bar() then bar chart may look like this:



The elegance of ggplot functions realizes in simple yet compact expression of visualization formula while hiding many options assumed by default. Hiding doesn't mean lacking as most options are just a step away. For example, for color color selection use one of the methods from the scale family of functions such as scale_fill_brewer():



And argument palette controls choice of colors in scale_fill_brewer():



Palettes used live in the package RColorBrewer - to see all available choices simply run display.brewer.all(): 



There are 3 types of palettes - sequential, diverging, and qualitative - each palette containing from 8 to 12 colors (see data frame brewer.pal.info or help ?RColorBrewer for more detail).

Curious reader may notice that if a bar chart contains 13 or more bars we get in trouble with colors like in the next plot:



Indeed length(unique(mtcars$hp)) finds 22 unique values for the attribute horse power, while the palette Set2 has 8 colors to choose from. Lack of colors in the palette triggers ggplot to issue warning like this (and invalidates plot as seen above):
1: In brewer.pal(n, pal) :
  n too large, allowed maximum for palette Set2 is 8
Returning the palette you asked for with that many colors
RColorBrewer gives us a way to produce larger palettes by interpolating existing ones with constructor function colorRampPalette(). It generates a function that does actual job of build palettes with arbitrary number of colors by interpolating existing palette. Thus expanding the palette Set1 of 9 colors to 22 (the number of unique horse power values in mtcars):


While we addressed color palette deficiency other interesting things happened: even though all bars are back and are distinctly colored we lost the color legend. I intentionally added theme(legend.position=...) to showcase this fact: despite explicit position request in theme() the legend is no more part of the plot.

The difference: fill parameter was moved outside of histogram aes() function which effectively removed color information from ggplot() aesthetics mapping. Hence, there is nothing to apply legend to.


To fix move fill back into aes() and use scale_fill_manual() to define custom palette:





Another likely problem with large number of bars in plots like above is placing and layout of the legend. Adjust legend position and layout using theme() and guide_legend() functions as follows:




Finally, the same example using  in place palette constructor with different choice of library palette:



There are quite a few more scale functions to choose from depending on aesthetics type (colour, fill), color types (gradient, hue, etc.), data values (discrete or continuous).

UPDATE (09.16.17)
Not to undermine usefulness of RColorBrewer but there are more choices available in R. One example is package ggthemes that besides offering complete themes and scales for ggplot2 contains themed color palettes:  




Wednesday, July 31, 2013

Quick R tip: ggplot in functions needs some extra care

When building visualizations with ggplot2 in R I decided to create specialized functions that encapsulate plotting logic for some of my creations. In this case instead of commonly used aes function I had to use its alternative -  aes_string - for aesthetic mapping from a string.

And now goes this handy tip:
while original aesthetic mapping function aes accepts x and y parameters by position:

p = ggplot(data, aes(x, y)) + ...

aes_string even though silently accepts them won't work like this:

my_plot_fun = function(data, xname, yname) {
  p = ggplot(data, aes_string(xname, yname)) + ...
}

It will run to compile plot object without problems but when plot p (returned from the function my_plot_fun) executed this rather cryptic error appears:

Error in as.environment(where) : 'where' is missing

What it means is that ggplot never got aesthetics defined right. This is due to aes_string function lacking the same position parameters as in its aes counterpart above. Instead, define both x and y parameters (and others if necessary) by name:

p = ggplot(data, aes_string(x=xname, y=yname)) + ...

Created by Pretty R at inside-R.org


UPDATE:


One more vote for using aes_string in place of aes comes from CRAN submission policy, i.e.:
In principle, packages must pass R CMD check without warnings or significant notes to be admitted to the main CRAN package area. If there are warnings or notes you cannot eliminate (for example because you believe them to be spurious) send an explanatory note as part of your covering email, or as a comment on the submission form. 
 (source: CRAN Repository Policy)
 What happens is that  R CMD check  reports notes like this for every aes call:

no visible binding for global variable [variable name]
It turns out that the most sensible solution is using aes_string instead.