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:
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!
mtcars
. Also, add a note that you have looked into other posts with a link, but they didn't work for your case, for x y z reasons. – zx8754