split fill in ggplot geom_tile (or heatmap): two colors by third value
<p>I have categorical data that I'd like to map the frequency of using a heatmap (geom_tile), much like the example below:</p>

<pre><code>data("mtcars")
freq &lt;- data.frame(xtabs(~cyl + gear, mtcars)) #count number of 4,6,8 cyl cars by gear
ggplot(freq, aes(cyl, gear)) +
  geom_tile(aes(fill = Freq)) + 
  scale_fill_gradient(low = "white",high = "steelblue")
</code></pre>

<p><img src="https://i.imgur.com/Gpezwrd.png" alt="standard frequency count heatmap"></p>

<p><strong>But I'd like to split each tile according to the proportion of significant or non-significant results (0-1 values).</strong> In this example, I would generate the same frequency count but differentiate between automatic and manual transmission (<code>am</code>)</p>

<pre><code>freq_am &lt;- data.frame(xtabs(~cyl + gear + am, mtcars))
print(freq_am)
   #cyl gear am Freq
      4    3  0    1
      6    3  0    2
      8    3  0   12
      4    4  0    2
      6    4  0    2
      8    4  0    0
      4    5  0    0
      6    5  0    0
      8    5  0    0
      4    3  1    0
      6    3  1    0
      8    3  1    0
      4    4  1    6
      6    4  1    2
      8    4  1    0
      4    5  1    2
      6    5  1    1
      8    5  1    2
</code></pre>

<p>The resulting heatmap would have (for example) <em>blue</em> for values of <code>am==0</code> and <em>red</em> for <code>am==1</code>. Each tile would be divided (along a diagonal?) according to the proportion of cars of that type that are automatic (<code>am==0</code>) or manual (<code>am==1</code>). The shades of blue and red would be proportionate to the count, just as the gradient already reflects.</p>

<p><em>For example:</em></p>

<ul>
<li><p>the top left tile (4,5) would be completely light red because all of the 4-cyl, 5-gear cars (count = 2) are manual</p></li>
<li><p>the middle left tile (4,4) would be 1/4 blue and 3/4 red because 25% of the 4-gear, 4-cyl cars are automatic (count = 2) and 75% are manual (count = 6)</p></li>
<li><p>the bottom left tile (4,3) would be completely lightest blue because all of the 4-cyl, 3-gear cars (count = 1) are automatic</p></li>
</ul>