<p><a href="https://twitter.com/drsimonj">@drsimonj</a> here to share my approach for visualizing individual observations with group means in the same plot. Here are some examples of what we’ll be creating:</p>
<p><a href="https://svbtleusercontent.com/qbba8b8qqws1wa.png"></a></p>
<p><a href="https://svbtleusercontent.com/6mix83lzegvla.png"></a></p>
<p><a href="https://svbtleusercontent.com/xcexi7wk8xsj1w.png"></a></p>
<p>I find these sorts of plots to be incredibly useful for visualizing and gaining insight into our data. We often visualize group means only, sometimes with the likes of standard errors bars. Alternatively, we plot only the individual observations using histograms or scatter plots. Separately, these two methods have unique problems. For example, we can’t easily see sample sizes or variability with group means, and we can’t easily see underlying patterns or trends in individual observations. But when individual observations and group means are combined into a single plot, we can produce some powerful visualizations.</p>
<h2><a href="https://drsimonj.svbtle.com/#general-approach_2"> </a>General approach</h2>
<p>Below is generic pseudo-code capturing the approach that we’ll cover in this post. Following this will be some worked examples of diving deeper into each component.</p>
<pre><code># Packages we need
library(ggplot2)
library(dplyr)

# Have an individual-observation data set
id

# Create a group-means data set
gd &lt;- id %>% 
        group_by(GROUPING-VARIABLES) %>% 
        summarise(
          VAR1 = mean(VAR1),
          VAR2 = mean(VAR2),
          ...
        )

# Plot both data sets
ggplot(id, aes(GEOM-AESTHETICS)) +
  geom_*() +
  geom_*(data = gd)

# Adjust plot to effectively differentiate data layers 
</code></pre>
<h2><a href="https://drsimonj.svbtle.com/#tidyverse-packages_2"> </a>Tidyverse packages</h2>
<p>Throughout, we’ll be using packages from the tidyverse: ggplot2 for plotting, and dplyr for working on the data. Let’s load these into our session:</p>
<pre><code>library(ggplot2)
library(dplyr)
</code></pre>
<h2><a href="https://drsimonj.svbtle.com/#group-means-on-a-single-variable_2"> </a>Group means on a single variable</h2>
<p>To get started, we’ll examine the logic behind the pseudo code with a simple example of presenting group means on a single variable. Let’s use <code>mtcars</code> as our individual-observation data set, <code>id</code>:</p>
<pre><code>id &lt;- mtcars %>% tibble::rownames_to_column() %>% as_data_frame()
id
#> # A tibble: 32 × 12
#>              rowname   mpg   cyl  disp    hp  drat    wt  qsec    vs    am
#>                &lt;chr> &lt;dbl> &lt;dbl> &lt;dbl> &lt;dbl> &lt;dbl> &lt;dbl> &lt;dbl> &lt;dbl> &lt;dbl>
#> 1          Mazda RX4  21.0     6 160.0   110  3.90 2.620 16.46     0     1
#> 2      Mazda RX4 Wag  21.0     6 160.0   110  3.90 2.875 17.02     0     1
#> 3         Datsun 710  22.8     4 108.0    93  3.85 2.320 18.61     1     1
#> 4     Hornet 4 Drive  21.4     6 258.0   110  3.08 3.215 19.44     1     0
#> 5  Hornet Sportabout  18.7     8 360.0   175  3.15 3.440 17.02     0     0
#> 6            Valiant  18.1     6 225.0   105  2.76 3.460 20.22     1     0
#> 7         Duster 360  14.3     8 360.0   245  3.21 3.570 15.84     0     0
#> 8          Merc 240D  24.4     4 146.7    62  3.69 3.190 20.00     1     0
#> 9           Merc 230  22.8     4 140.8    95  3.92 3.150 22.90     1     0
#> 10          Merc 280  19.2     6 167.6   123  3.92 3.440 18.30     1     0
#> # ... with 22 more rows, and 2 more variables: gear &lt;dbl>, carb &lt;dbl>
</code></pre>
<p>Say we want to plot cars’ horsepower (<code>hp</code>), separately for automatic and manual cars (<code>am</code>). Let’s quickly convert <code>am</code> to a factor variable with proper labels:</p>
<pre><code>id &lt;- id %>% mutate(am = factor(am, levels = c(0, 1), labels = c(&quot;automatic&quot;, &quot;manual&quot;)))
</code></pre>
<p>Using the individual observations, we can plot the data as points via:</p>
<pre><code>ggplot(id, aes(x = am, y = hp)) +
  geom_point()
</code></pre>
<p><a href="https://svbtleusercontent.com/5zeinyig3qozuq.png"></a></p>
<p>What if we want to visualize the means for these groups of points? We start by computing the mean horsepower for each transmission type into a new group-means data set (<code>gd</code>) as follows:</p>
<pre><code>gd &lt;- id %>% 
        group_by(am) %>% 
        summarise(hp = mean(hp))
gd
#> # A tibble: 2 × 2
#>          am       hp
#>      &lt;fctr>    &lt;dbl>
#> 1 automatic 160.2632
#> 2    manual 126.8462
</code></pre>
<p>There are a few important aspects to this:</p>
<ul><li> We group our individual observations by the categorical variable using <code>group_by()</code>.</li>
<li> We <code>summarise()</code> the variable as its <code>mean()</code>.</li>
<li> We give the summarized variable the same name in the new data set. E.g., <code>hp = mean(hp)</code> results in <code>hp</code> being in both data sets.</li>
</ul><p>We could plot these means as bars via:</p>
<pre><code>ggplot(gd, aes(x = am, y = hp)) +
  geom_bar(stat = &quot;identity&quot;)
</code></pre>
<p><a href="https://svbtleusercontent.com/nbuho95hcy8sw.png"></a></p>
<p>The challenge now is to combine these plots.</p>
<p>As the base, we start with the individual-observation plot:</p>
<pre><code>ggplot(id, aes(x = am, y = hp)) +
  geom_point()
</code></pre>
<p><a href="https://svbtleusercontent.com/b5ire4kqanta5g.png"></a></p>
<p>Next, to display the group-means, we add a geom layer specifying <code>data = gd</code>. In this case, we’ll specify the <code>geom_bar()</code> layer as above:</p>
<pre><code>ggplot(id, aes(x = am, y = hp)) +
  geom_point() +
  geom_bar(data = gd, stat = &quot;identity&quot;)
</code></pre>
<p><a href="https://svbtleusercontent.com/jzvlutdplhyxkq.png"></a></p>
<p>Although there are some obvious problems, we’ve successfully covered most of our pseudo-code and have individual observations and group means in the one plot.</p>
<p>Before we address the issues, let’s discuss how this works. The main point is that our base layer (<code>ggplot(id, aes(x = am, y = hp))</code>) specifies the variables (<code>am</code> and <code>hp</code>) that are going to be plotted. By including <code>id</code>, it also means that any geom layers that follow without specifying <code>data</code>, will use the individual-observation data. Thus, <code>geom_point()</code> plots the individual points. <code>geom_bar()</code>, however, specifies <code>data = gd</code>, meaning it will try to use information from the group-means data. Because our group-means data has the same variables as the individual data, it can make use of the variables mapped out in our base <code>ggplot()</code> layer.</p>
<p>At this point, the elements we need are in the plot, and it’s a matter of adjusting the visual elements to differentiate the individual and group-means data and display the data effectively overall. Among other adjustments, this typically involves paying careful attention to the order in which the geom layers are added, and making heavy use of the alpha (transparency) values.</p>
<p>For example, we can make the bars transparent to see all of the points by reducing the <code>alpha</code> of the bars:</p>
<pre><code>ggplot(id, aes(x = am, y = hp)) +
  geom_point() +
  geom_bar(data = gd, stat = &quot;identity&quot;, alpha = .3)
</code></pre>
<p><a href="https://svbtleusercontent.com/o2vd45cqrv0xq.png"></a></p>
<p>Here’s a final polished version that includes:</p>
<ul><li> Color to the bars and points for visual appeal.</li>
<li> <code>ggrepel::geom_text_repel</code> to add car labels to each point.</li>
<li> <code>theme_bw()</code> to clean the overall appearance.</li>
<li> Proper axis labels.</li>
</ul><pre><code>ggplot(id, aes(x = am, y = hp, color = am, fill = am)) +
  geom_bar(data = gd, stat = &quot;identity&quot;, alpha = .3) +
  ggrepel::geom_text_repel(aes(label = rowname), color = &quot;black&quot;, size = 2.5, segment.color = &quot;grey&quot;) +
  geom_point() +
  guides(color = &quot;none&quot;, fill = &quot;none&quot;) +
  theme_bw() +
  labs(
    title = &quot;Car horespower by transmission type&quot;,
    x = &quot;Transmission&quot;,
    y = &quot;Horsepower&quot;
  )
</code></pre>
<p><a href="https://svbtleusercontent.com/buei1ahzmcuwww.png"></a></p>
<p>Notice that, again, we can specify how variables are mapped to aesthetics in the base <code>ggplot()</code> layer (e.g., <code>color = am</code>), and this affects the individual and group-means geom layers because both data sets have the same variables.</p>
<h2><a href="https://drsimonj.svbtle.com/#group-means-on-two-variables_2"> </a>Group means on two variables</h2>
<p>Next, we’ll move to overlaying individual observations and group means for two continuous variables. This time we’ll use the <code>iris</code> data set as our individual-observation data:</p>
<pre><code>id &lt;- as_data_frame(iris)
id
#> # A tibble: 150 × 5
#>    Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#>           &lt;dbl>       &lt;dbl>        &lt;dbl>       &lt;dbl>  &lt;fctr>
#> 1           5.1         3.5          1.4         0.2  setosa
#> 2           4.9         3.0          1.4         0.2  setosa
#> 3           4.7         3.2          1.3         0.2  setosa
#> 4           4.6         3.1          1.5         0.2  setosa
#> 5           5.0         3.6          1.4         0.2  setosa
#> 6           5.4         3.9          1.7         0.4  setosa
#> 7           4.6         3.4          1.4         0.3  setosa
#> 8           5.0         3.4          1.5         0.2  setosa
#> 9           4.4         2.9          1.4         0.2  setosa
#> 10          4.9         3.1          1.5         0.1  setosa
#> # ... with 140 more rows
</code></pre>
<p>Let’s say we want to visualize the petal length and width for each iris <code>Species</code>.</p>
<p>Let’s create the group-means data set as follows:</p>
<pre><code>gd &lt;- id %>% 
        group_by(Species) %>% 
        summarise(Petal.Length = mean(Petal.Length),
                  Petal.Width  = mean(Petal.Width))
gd
#> # A tibble: 3 × 3
#>      Species Petal.Length Petal.Width
#>       &lt;fctr>        &lt;dbl>       &lt;dbl>
#> 1     setosa        1.462       0.246
#> 2 versicolor        4.260       1.326
#> 3  virginica        5.552       2.026
</code></pre>
<p>We’ve now got the variable means for each Species in a new group-means data set, <code>gd</code>. The important point, as before, is that there are the same variables in <code>id</code> and <code>gd</code>.</p>
<p>Let’s prepare our base plot using the individual observations, <code>id</code>:</p>
<pre><code>ggplot(id, aes(x = Petal.Length, y = Petal.Width)) +
  geom_point()
</code></pre>
<p><a href="https://svbtleusercontent.com/9yjtrtmjv7hhdg.png"></a></p>
<p>Let’s use the color aesthetic to distinguish the groups:</p>
<pre><code>ggplot(id, aes(x = Petal.Length, y = Petal.Width, color = Species)) +
  geom_point()
</code></pre>
<p><a href="https://svbtleusercontent.com/oaps1sq4wf30a.png"></a></p>
<p>Now we can add a geom that uses our group means. We’ll use <code>geom_point()</code> again:</p>
<pre><code>ggplot(id, aes(x = Petal.Length, y = Petal.Width, color = Species)) +
  geom_point() +
  geom_point(data = gd)
</code></pre>
<p><a href="https://svbtleusercontent.com/4xu4xhgrzrkmgq.png"></a></p>
<p>Did it work? Well, yes, it did. The problem is that we can’t distinguish the group means from the individual observations because the points look the same. Again, we’ve successfully integrated observations and means into a single plot. The challenge now is to make various adjustments to highlight the difference between the data layers.</p>
<p>To do this, we’ll fade out the observation-level geom layer (using <code>alpha</code>) and increase the <code>size</code> of the group means:</p>
<pre><code>ggplot(id, aes(x = Petal.Length, y = Petal.Width, color = Species)) +
  geom_point(alpha = .4) +
  geom_point(data = gd, size = 4)
</code></pre>
<p><a href="https://svbtleusercontent.com/bc4jcjtmwklm8g.png"></a></p>
<p>Here’s a final polished version for you to play around with:</p>
<pre><code>ggplot(id, aes(x = Petal.Length, y = Petal.Width, color = Species, shape = Species)) +
  geom_point(alpha = .4) +
  geom_point(data = gd, size = 4) +
  theme_bw() +
  guides(color = guide_legend(&quot;Species&quot;),  shape = guide_legend(&quot;Species&quot;)) +
  labs(
    title = &quot;Petal size of iris species&quot;,
    x = &quot;Length&quot;,
    y = &quot;Width&quot;
  )
</code></pre>
<p><a href="https://svbtleusercontent.com/74py43oonkekqw.png"></a></p>
<h2><a href="https://drsimonj.svbtle.com/#repeated-observations_2"> </a>Repeated observations</h2>
<p>One useful avenue I see for this approach is to visualize repeated observations. For example, colleagues in my department might want to plot depression levels measured at multiple time points for people who receive one of two types of treatment. Typically, they would present the means of the two groups over time with error bars. However, we can improve on this by also presenting the individual trajectories.</p>
<p>As an example, let’s examine changes in healthcare expenditure over five years (from 2001 to 2005) for countries in Oceania and the Europe.</p>
<p>Start by gathering our individual observations from my new <a href="https://github.com/drsimonj/ourworldindata">ourworldindata package for R</a>, which you can learn more about in a <a href="https://goo.gl/1EQX94">previous blogR post</a>:</p>
<pre><code># Individual-observations data
library(ourworldindata)
id &lt;- financing_healthcare %>% 
        filter(continent %in% c(&quot;Oceania&quot;, &quot;Europe&quot;) &amp; between(year, 2001, 2005)) %>% 
        select(continent, country, year, health_exp_total) %>% 
        na.omit()
id
#> # A tibble: 275 × 4
#>    continent country  year health_exp_total
#>        &lt;chr>   &lt;chr> &lt;int>            &lt;dbl>
#> 1     Europe Albania  2001         198.2242
#> 2     Europe Albania  2002         225.1861
#> 3     Europe Albania  2003         236.3563
#> 4     Europe Albania  2004         263.5986
#> 5     Europe Albania  2005         276.6520
#> 6     Europe Andorra  2001        1432.2798
#> 7     Europe Andorra  2002        1564.6976
#> 8     Europe Andorra  2003        1601.0641
#> 9     Europe Andorra  2004        1661.5608
#> 10    Europe Andorra  2005        1793.9938
#> # ... with 265 more rows
</code></pre>
<p>Let’s plot these individual country trajectories:</p>
<pre><code>ggplot(id, aes(x = year, y = health_exp_total)) +
  geom_line()
</code></pre>
<p><a href="https://svbtleusercontent.com/oak12um1squ0g.png"></a></p>
<p>Hmm, this doesn’t look like right. The problem is that we need to <code>group</code> our data by <code>country</code>:</p>
<pre><code>ggplot(id, aes(x = year, y = health_exp_total, group = country)) +
  geom_line()
</code></pre>
<p><a href="https://svbtleusercontent.com/fseanbxgq2ra.png"></a></p>
<p>We now have a separate line for each country. Let’s <code>color</code> these depending on the world region (<code>continent</code>) in which they reside:</p>
<pre><code>ggplot(id, aes(x = year, y = health_exp_total, group = country, color = continent)) +
  geom_line()
</code></pre>
<p><a href="https://svbtleusercontent.com/6hrmkequilixmg.png"></a></p>
<p>If we tried to follow our usual steps by creating group-level data for each world region and adding it to the plot, we would do something like this:</p>
<pre><code>gd &lt;- id %>% 
        group_by(continent) %>% 
        summarise(health_exp_total = mean(health_exp_total))

ggplot(id, aes(x = year, y = health_exp_total, group = country, color = continent)) +
  geom_line() +
  geom_line(data = gd)
</code></pre>
<p>This, however, will lead to a couple of errors, which are both caused by variables being called in the base <code>ggplot()</code> layer, but not appearing in our group-means data, <code>gd</code>.</p>
<p>First, we’re not taking <code>year</code> into account, but we want to! In this case, <code>year</code> must be treated as a second grouping variable, and included in the <code>group_by</code> command. Thus, to compute the relevant group-means, we need to do the following:</p>
<pre><code>gd &lt;- id %>% 
        group_by(continent, year) %>% 
        summarise(health_exp_total = mean(health_exp_total))
gd
#> Source: local data frame [10 x 3]
#> Groups: continent [?]
#> 
#>    continent  year health_exp_total
#>        &lt;chr> &lt;int>            &lt;dbl>
#> 1     Europe  2001        1196.7948
#> 2     Europe  2002        1311.2303
#> 3     Europe  2003        1375.2729
#> 4     Europe  2004        1465.5530
#> 5     Europe  2005        1550.2395
#> 6    Oceania  2001         398.1582
#> 7    Oceania  2002         414.7088
#> 8    Oceania  2003         448.6919
#> 9    Oceania  2004         475.8466
#> 10   Oceania  2005         501.5413
</code></pre>
<p>The second error is because we’re grouping lines by <code>country</code>, but our group means data, <code>gd</code>, doesn’t contain this information. Thus, we need to move <code>aes(group = country)</code> into the geom layer that draws the individual-observation data.</p>
<p>Now, our plot will be:</p>
<pre><code>ggplot(id, aes(x = year, y = health_exp_total, color = continent)) +
  geom_line(aes(group = country)) +
  geom_line(data = gd)
</code></pre>
<p><a href="https://svbtleusercontent.com/bjsvtqritwaxg.png"></a></p>
<p>It worked again; we just need to make the necessary adjustments to see the data properly. Here’s a polished final version of the plot. See if you can work it out!</p>
<pre><code>ggplot(id, aes(x = year, y = health_exp_total, color = continent)) +
  geom_line(aes(group = country), alpha = .3) +
  geom_line(data = gd, alpha = .8, size = 3) +
  theme_bw() +
  labs(
    title = &quot;Changes in healthcare spending\nacross countries and world regions&quot;,
    x = NULL,
    y = &quot;Total healthcare investment ($)&quot;,
    color = NULL
  )
</code></pre>
<p><a href="https://svbtleusercontent.com/qr9jwm7dkw1xiq.png"></a></p>
<h2><a href="https://drsimonj.svbtle.com/#final-challenge_2"> </a>Final challenge</h2>
<p>For me, in a scientific paper, I like to draw time-series like the example above using the <a href="https://drsimonj.svbtle.com/mean-and-ci-plot-for-twoway-designs-using-ggplot2">line plot described in another blogR post</a>. As a challenge, I’ll leave it to you to draw this sort of neat time series with individual trajectories drawn underneath the mean trajectories with error bars. Don’t hesitate to get in touch if you’re struggling. Even better, succeed and tweet the results to let me know by including <a href="https://twitter.com/drsimonj">@drsimonj</a>!</p>
<h2><a href="https://drsimonj.svbtle.com/#sign-off_2"> </a>Sign off</h2>
<p>Thanks for reading and I hope this was useful for you.</p>
<p>For updates of recent blog posts, follow <a href="https://twitter.com/drsimonj">@drsimonj</a> on Twitter, or email me at <a href="mailto:drsimonjackson@gmail.com">drsimonjackson@gmail.com</a> to get in touch.</p>
<p>If you’d like the code that produced this blog, check out the <a href="https://github.com/drsimonj/blogR">blogR GitHub repository</a>.</p>