title: Stacked and grouped barplots
body: <p>I want to make a stacked and grouped barplot. I would like to manage in base R. As my output I would like to present &quot;R&quot;, and &quot;W&quot; next to each other for each id. I want each stack to be named R/W and underneath it should say which id it belongs to. Does anyone have a suggestion of how to manage this? Thanks!</p>
  <pre><code> id &lt;- rep(1:10,each=2)
  
  trt &lt;- rep(c(&quot;R&quot;,&quot;W&quot;), 2)
  set.seed(1)
  A &lt;- sample(100,10)
  set.seed(2)
  B &lt;- sample(100,10)
  
  df &lt;- data.frame(id,trt,A,B)
  df
  
  dfR &lt;- df[df$trt==&quot;R&quot;,]
  rownames(dfR) &lt;- dfR$id
  
  par(mar=c(3,2,2,5))
  par(mfrow=c(2,1))
    
  co &lt;- c(&quot;red&quot;, &quot;blue&quot;)
  dfR_ &lt;- t(as.matrix(dfR[,-c(1,2)]))
  barplot(dfR_, main=&quot;R&quot;,
          xlab=&quot;nmol/L&quot;, col=co)
  
  
  r&lt;- rev((rownames(dfR_)))
  legend(&quot;topright&quot;, inset=c(-0.1,0.15), legend=r, pch=15, col=rev(co))
  
  
  dfR &lt;- df[df$trt==&quot;W&quot;,]
  rownames(dfR) &lt;- dfR$id
  
  co &lt;- c(&quot;red&quot;, &quot;blue&quot;)
  dfR_ &lt;- t(as.matrix(dfR[,-c(1,2)]))
  barplot(dfR_, main=&quot;W&quot;,
          xlab=&quot;nmol/L&quot;, col=co)
  
  par(mar=c(3,2,2,5))
  
  r&lt;- rev((rownames(dfR_)))
  legend(&quot;topright&quot;, inset=c(-0.1,0.15), legend=r, pch=15, col=rev(co))
  </code></pre>
  <p><a href="https://i.stack.imgur.com/H3hvX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/H3hvX.png" alt="enter image description here" /></a></p>