# How do you create a stacked bar graph in R?

**URL:** <https://boards.straightdope.com/t/how-do-you-create-a-stacked-bar-graph-in-r/662823>\
**Category:** Factual Questions\
**Created:** [July 6, 2013, 11:35pm UTC](https://boards.straightdope.com/t/how-do-you-create-a-stacked-bar-graph-in-r/662823 "2013-07-06T23:35:24Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![F.Pu-du-he-pa-as](https://avatars.discourse-cdn.com/v4/letter/f/c89c15/32.png) [@F.Pu-du-he-pa-as](https://boards.straightdope.com/u/F.Pu-du-he-pa-as)\
**Post date:** [July 6, 2013, 11:35pm UTC](https://boards.straightdope.com/t/how-do-you-create-a-stacked-bar-graph-in-r/662823/1 "2013-07-06T23:35:24Z")

</div>

So, I’ve been learning R for less than two weeks, and I’m trying to make a stacked bar graph. It is…more or less not working out. I found [this page](http://www.statmethods.net/graphs/bar.html), which looks like it has the information I need, but I am just too much of a blockhead to understand what the code means and what exactly it’s asking for.

> [@](#):
>
> # Stacked Bar Plot with Colors and Legend
> 
> counts \<- table(mtcars$vs, mtcars$gear)  
> barplot(counts, main=“Car Distribution by Gears and VS”,  
> xlab=“Number of Gears”, col=c(“darkblue”,“red”),  
> legend = rownames(counts))

Could anyone help me understand this?

---

<div class="post-metadata">

**Author:** ![Nametag](https://sea3.discourse-cdn.com/straightdope/user_avatar/boards.straightdope.com/nametag/32/406_2.png) [@Nametag](https://boards.straightdope.com/u/Nametag)\
**Post date:** [July 7, 2013, 3:05am UTC](https://boards.straightdope.com/t/how-do-you-create-a-stacked-bar-graph-in-r/662823/2 "2013-07-07T03:05:05Z")

</div>

**counts \<- table(mtcars$vs, mtcars$gear)** This part defines a table (mtcars) as the source of your data. The variables are vs and gear.

**barplot(counts,** This part specifies a barplot with the data from the table controlling the height of the bars.

**main=“Car Distribution by Gears and VS”,** This part defines the main title.

**xlab=“Number of Gears”,** This part labels your X-axis.

**col=c(“darkblue”,“red”),** This part colors the stack, using a dataframe.

\*\*legend = rownames(counts)) \*\* And this part creates a legend using the names of the rows in the table.

Read the rest of that website might give you a bit more insight.
