我调查了类似的问题,但是没有运气。这是一个示例数据集,但我仅使用Sex和Weight变量。
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")
我需要创建一个显示男性和女性体重计数的条形图。我为此使用ggplot并创建了一个堆叠的直方图:
ggplot的代码很简单:
ggplot(data = data, aes(x = Weight, fill = Sex)) +
geom_histogram(binwidth = 10, position="stack")
但是,我不知道如何使用基数R创建相似的图。我试图创建一个具有重量和性别的表格,然后绘制图形,这是此链接的一种解决方案:Stacked Histograms Using R Base Graphics >
tab <- table(data$Sex,data$Weight)
barplot(tab)
但是由于Weight是连续变量,它返回了一个带有太多条形图的图形: the graph has too many bars
我还尝试了hist(tab)
和hist(data$Weight)
,这显然也不正确。
如何使用基数R重新创建图形?谢谢!
答案 0 :(得分:1)
您的示例数据中没有足够的观察结果,因此我只使用rnorm
:
x <- rnorm(100, 10, 1)
y <- rnorm(100, 12, 1)
使用plot
来堆积直方图:
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")