R和ggplot - 情节分布和线

时间:2015-11-05 06:36:17

标签: r plot ggplot2

我有一个看似非常简单的问题,但我似乎无法弄明白。我有一个给定年份的治疗数据集。有3种不同的治疗方法。我想创建两个图:

看起来像这样:

area plot

看起来像这样:

scatter plot

,除了,我想堆叠多个处理(三个而不仅仅是示例中的一个)。

假设我们有以下df:

y=c(2001,2001,2001,2001,2002,2002,2002,2003,2003,2003,2003,2004,2004)
t=c("a","a","b","c","a","a","b","c","a","a","b","c","b")
df=data.frame(y,t)

我尝试过使用

geom_plot()

但它不起作用。我可以得到R最接近我的比例是使用来自另一个帖子的代码的以下堆积直方图:

p+geom_histogram(aes(y=..density.., color=t , fill=t))

1 个答案:

答案 0 :(得分:1)

对于您显示的图表类型,您需要在绘制之前计算比例。 table函数可用于按年tt计算avesum y geom_area library(ggplot2) y=c(2001,2001,2001,2001,2002,2002,2002,2003,2003,2003,2003,2004,2004) t=c("a","a","b","c","a","a","b","c","a","a","b","c","b") df=data.frame(y, t) # Count number of t's by year df_tab <- as.data.frame(table(df), stringsAsFactors=FALSE) # convert counts to percents df <- data.frame(df_tab, p=df_tab$Freq/ave(df_tab$Freq, df_tab$y, FUN=sum)) df$y <- as.numeric(df$y) # Set plot colors and themes plot_colours <- c(a="red3", b = "orange", c = "blue") plot_theme <- theme(axis.title = element_text(size = 18 )) + theme(axis.text = element_text(size = 18)) + theme(legend.position="top", legend.text=element_text(size=18)) # make area plot sp <- ggplot(data=df, aes(x=y, y= 100*p, fill=t)) + geom_area() sp <- sp + scale_fill_manual(values=plot_colours) sp <- sp + labs(x="Year", y = "Percentage of Patients") sp <- sp + plot_theme plot(sp) # make line plot sp <- ggplot(data=df, aes(x=y, y=p, colour=t)) sp <- sp + geom_line(aes(ymax=1), position="stack", size=1.05) + geom_point(aes(ymax=1), position="stack", size=4) sp <- sp + scale_colour_manual(values=plot_colours) sp <- sp + labs(x="Year", y = "Proportion Receiving Treatment") sp <- sp + plot_theme plot(sp) 然后计算比例的年度总和。您的第一个图是使用<ul id="specialitycenters" class="specialitycenters" name="specialty-centers"> <li class="selected">ARCH At Risk Children Center</li> <li class="selected">ARMS Primary care services for HIV AIDS</li> <li class="selected">Adolescent - Young Adult Medicine</li> <li>After the Cancer Experience ACE Late Effects Clinic Long Term Followup</li> <li>Allergy</li> <li>Allergy and Immunology</li> <li>Analytical Imaging Modeling Center AIM</li> <li>Anesthesiology</li> <li>Comprehensive Stone Program</li> </ul> 创建的,而第二个图是标准的线和点图。代码看起来像

if (PK.ToString() == "id" || "Id" || "ID" || "iD"))
{

}

产生情节 enter image description here

enter image description here