我正在尝试制作堆积区域图。我的x轴是年龄类别,但我想将它们连接成一个连续的比例。
我对y(诊断时填写)和x上的年龄有多少诊断。
数据子集:
structure(list(diag = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("Hjernerystelse",
"Lungesygdomme"), class = "factor"), age = structure(c(1L, 2L,
4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 3L, 12L, 13L, 14L, 15L, 16L,
17L, 18L, 19L, 1L, 2L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 3L,
12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L), .Label = c("0 år", "1-4 år",
"5-9 år", "10-14 år", "15-19 år", "20-24 år", "25-29 år", "30-34 år",
"35-39 år", "40-44 år", "45-49 år", "50-54 år", "55-59 år", "60-64 år",
"65-69 år", "70-74 år", "75-79 år", "80-84 år", "85- år"), class = "factor"),
n = c(15L, 89L, 87L, 71L, 46L, 32L, 26L, 24L, 32L, 40L, 74L,
55L, 39L, 19L, 38L, 27L, 24L, 14L, 23L, 291L, 2170L, 267L,
269L, 234L, 244L, 256L, 336L, 432L, 638L, 458L, 792L, 1010L,
1401L, 2088L, 2087L, 1815L, 1767L, 1995L)), row.names = c(NA,
-38L), .Names = c("diag", "age", "n"), class = c("tbl_df", "tbl",
"data.frame"))
下面给出了一个有用的图,但没有保留x轴上的类别:
plot1 <- ggplot(foo, aes(age, n)) +
geom_area(aes(x=as.numeric(factor(age)), fill=diag))
是否有一种简单的方法可以在因子数据上使用geom_area,或者只是一种在x轴上显示水平的方法。
另一个问题是,数据有29种不同的诊断结果:
答案 0 :(得分:3)
尝试这种方法:
library(directlabels)
ggplot(foo, aes(x=as.numeric(factor(age)), y = n, fill=diag)) +
geom_area() +
scale_x_discrete(labels = levels(foo$age)) +
geom_dl(aes(label = diag), list("top.points", cex = .6)) +
guides(fill = FALSE)
关于您的评论,请尝试此
download.file("https://dl.dropboxusercontent.com/u/12226044/admissions.Rdata",
destfile = fn <- file.path(tempdir(), "admissions.Rdata"),
mode = "wb")
load(fn)
library(ggplot2)
library(directlabels)
library(dplyr)
shaped %>%
group_by(diag, age) %>%
summarise(n = mean(n)) %>%
ggplot(aes(x=as.numeric(factor(age)), y = n, fill=diag)) +
geom_area(position = "stack") +
scale_x_discrete(labels = levels(shaped$age), expand = c(.1, .1)) +
geom_dl(aes(label = diag, color = diag), position = "stack", list("last.bumpup", rot=-30, cex = .5)) +
guides(fill = FALSE, colour = FALSE)