Reverse stacking order without affecting legend order in ggplot2 bar charts
<p><a href="https://stackoverflow.com/questions/2427742/how-do-i-change-the-stacking-order-in-a-bar-chart-in-ggplot2">How do I change the stacking order in a bar chart in ggplot2?</a> shows how to reverse the stacking order, but the <a href="https://stackoverflow.com/a/38423485/1840471">solution</a> also changes the order shown in the legend. I'd like to change the stacking order without affecting the legend order, such that the top class in the legend is also the top class in stacking.</p>

<pre><code>library(ggplot2)
data(mtcars)
ggplot(mtcars, aes(factor(cyl), fill=gear)) + geom_bar()
</code></pre>

<p><a href="https://i.stack.imgur.com/T9H6N.png" rel="noreferrer"><img src="https://i.stack.imgur.com/T9H6N.png" alt="Original column chart using &lt;code&gt;ggplot2::ggplot&lt;/code&gt;"></a></p>

<p>To reverse the stacking order, reverse the factor levels. This also reverses the legend order.</p>

<pre><code>mtcars$gear &lt;- factor(mtcars$gear)  # First make factor with default levels
mtcars$gear &lt;- factor(mtcars$gear, levels=rev(levels(mtcars$gear)))
ggplot(mtcars, aes(factor(cyl), fill=gear)) + geom_bar()
</code></pre>

<p><a href="https://i.stack.imgur.com/T9H6N.png" rel="noreferrer"><img src="https://i.stack.imgur.com/VqOXQ.png" alt="Reversed column chart"></a></p>

<p><a href="https://stackoverflow.com/questions/22458970/how-to-reverse-legend-labels-and-color-so-high-value-starts-downstairs">How to reverse legend (labels and color) so high value starts downstairs?</a> suggests <code>guide_legend(reverse=T)</code> but isn't easily reproducible and doesn't pertain to stacked bar charts.</p>