Newbie using ggplot2 for stacked bar charts

I have this data :
Age Unksmrw Unkgtrw
1 0 0 0
2 2 758 172
3 3 1187 280
4 4 893 206
5 5 643 125
6 6 352 94
7 7 195 58
8 8 93 25
9 9 51 13
10 10 23 7
11 11 7 5
12 12 4 2
13 13 1 1
14 14 0 0
15 15 0 0
16 16 0 0
17 17 0 0
18 19 0 0
I want to create a stacked bar chart like this:
image
I've gone through the tutorial several times but nowhere do they have examples of this sort of data and stackoverflow answers all seem to require libraries I haven't got (reshape2?). It seems such a simple thing but it's mangling my brain trying to get the different axis to work!
Basically I want:
Age along the bottom.
Values of unksmrw and unkgtrw stacked vertically.
Any help gratefully received :slight_smile:

Bar charts — geom_bar • ggplot2 (tidyverse.org)

Thanks Martin. I'll work through this one.

reshape2 melt function is not that complicated to understand. I will recommend at least for you to give it a try. You can install reshape 2 very easily.
You can see what I did in my example dataset. We have data set of three columns age, Unksmrw, and Unkgtrw.
The melt function in this data stacks those two columns together. As Age is the one that will be in the X-axis which will be the identifier in this case.
You can remove as. factor (age) and just use age in ggplot() function, it will depend on what you want in the graph.

library(ggplot2)
library(reshape2)

example_data<- data.frame(age= c(6, 8, 9 , 10, 12),
Unksmrw = c(10, 12, 7, 13, 10),
Unkgtrw = c(15, 18, 16, 12, 10)
)

example_data
#>   age Unksmrw Unkgtrw
#> 1   6      10      15
#> 2   8      12      18
#> 3   9       7      16
#> 4  10      13      12
#> 5  12      10      10

example_long<- reshape2::melt(example_data, id.vars = "age")
example_long
#>    age variable value
#> 1    6  Unksmrw    10
#> 2    8  Unksmrw    12
#> 3    9  Unksmrw     7
#> 4   10  Unksmrw    13
#> 5   12  Unksmrw    10
#> 6    6  Unkgtrw    15
#> 7    8  Unkgtrw    18
#> 8    9  Unkgtrw    16
#> 9   10  Unkgtrw    12
#> 10  12  Unkgtrw    10

ggplot(example_long, aes( x= as.factor(age), y = value, fill = variable))+
  geom_bar(position="stack", stat="identity")

image
[image]

Created on 2021-03-28 by the reprex package (v0.3.0)

Thanks Binu, that's exactly what I wanted to do. You're right, reshape2 looks like it will be useful.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.