Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a stacked histogram using base R?

Tags:

r

I have looked into similar questions but had no luck. Here is a sample dataset, but I am only using Sex and Weight variable.

structure(list(Name = c("A Lamusi", "Juhamatti Tapio Aaltonen", 
"Andreea Aanei", "Jamale (Djamel-) Aarrass (Ahrass-)", "Nstor Abad Sanjun"
), Sex = c("M", "M", "F", "M", "M"), Age = c(23L, 28L, 22L, 30L, 
23L), Height = c(170L, 184L, 170L, 187L, 167L), Weight = c(60, 
85, 125, 76, 64), Team = c("China", "Finland", "Romania", "France", 
"Spain"), NOC = c("CHN", "FIN", "ROU", "FRA", "ESP"), Games = c("2012 Summer", 
"2014 Winter", "2016 Summer", "2012 Summer", "2016 Summer"), 
    Year = c(2012L, 2014L, 2016L, 2012L, 2016L), Season = c("Summer", 
    "Winter", "Summer", "Summer", "Summer"), City = c("London", 
    "Sochi", "Rio de Janeiro", "London", "Rio de Janeiro"), Sport = c("Judo", 
    "Ice Hockey", "Weightlifting", "Athletics", "Gymnastics"), 
    Event = c("Judo Men's Extra-Lightweight", "Ice Hockey Men's Ice Hockey", 
    "Weightlifting Women's Super-Heavyweight", "Athletics Men's 1,500 metres", 
    "Gymnastics Men's Individual All-Around"), Medal = c(NA, 
    "Bronze", NA, NA, NA), Num_Sports = c("Judo", "Ice Hockey", 
    "Weightlifting", "Athletics", "Gymnastics")), row.names = c("1", 
"2", "3", "4", "5"), class = "data.frame")

I need to create a barplot which displays the weight count of male and female. I used ggplot for that and created a stacked histogram plot:

enter image description here

The code for ggplot was easy:

ggplot(data = data, aes(x = Weight, fill = Sex)) + 
    geom_histogram(binwidth = 10, position="stack") 

However, I do not know how to create a similar plot using base R. I tried to create a table with weight and sex and then plot the graph, which is a solution from this link: Stacked Histograms Using R Base Graphics

tab <- table(data$Sex,data$Weight)
barplot(tab)

But it returned a graph with too many bars since Weight is a continuous variable: the graph has too many bars

I also tried hist(tab) and hist(data$Weight), which were obviously not correct either.

How can I re-create the graph using base R? Thank you!

like image 248
vvx Avatar asked Dec 08 '25 05:12

vvx


1 Answers

There aren't enough observations in your example data, so I'll just use rnorm:

x <- rnorm(100, 10, 1)
y <- rnorm(100, 12, 1)

Use the plot to stack your histograms:

h1 <- hist(x, breaks = 10)
h2 <- hist(y, breaks = 10)

par(mar=c(5.1, 4.1, 4.1, 8.1), xpd=TRUE)

plot(h1, col = "Red", xlim = c(6, 16), xlab = "Weight", main = NULL)
plot(h2, col = "Blue", xlim = c(6, 16), add = T)

legend(17, 19,c("f", "m"), fill = c("Red", "Blue"), title = "Sex")

stacked histograms


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!