Re-ordering bars in R's barplot()
<p>What I want to achieve is exactly the same that was already asked here (and specifically using R's base graphics, not packages like <code>ggplot</code> or <code>lattice</code>): <a href="https://stackoverflow.com/q/19681586">Ordering bars in barplot()</a></p>

<p>However, the solutions proposed there do not seem to work for me. What I need to is the following. Suppose I have this:</p>

<pre><code>num &lt;- c(1, 8, 4, 3, 6, 7, 5, 2, 11, 3)
cat &lt;- c(letters[1:length(num)])
data &lt;- data.frame(num, cat)
</code></pre>

<p>If I generate a barplot using <code>barplot(data$num)</code>, here is what I get:</p>

<p><a href="https://i.stack.imgur.com/BqUis.png" rel="noreferrer"><img src="https://i.stack.imgur.com/BqUis.png" alt=""></a></p>

<p>Now, I want to reorder the bars according to <code>data$cat</code>. Following the link I mentioned above, I tried the accepted answer but got an error:</p>

<pre><code>num2 &lt;- factor(num, labels = as.character(cat))
Error in factor(num, labels = as.character(cat)) : invalid 'labels'; length 10 should be 1 or 9
</code></pre>

<p>Then I also tried the other answer there:</p>

<pre><code>num &lt;- as.factor(num)
barplot(table(num))
</code></pre>

<p>But here is what I got:</p>

<p><a href="https://i.stack.imgur.com/pWV6F.png" rel="noreferrer"><img src="https://i.stack.imgur.com/pWV6F.png" alt=""></a></p>

<p>So, in this particular case of mine, which is slightly different from that question, <strong>how should I order the barplot so the bars are defined by <code>data$num</code> but ordered according to <code>data$cat</code>?</strong></p>