2015-11-05 81 views
1

我有一个问题,似乎很简单,但我似乎无法弄清楚。我有一个给定年份的治疗数据集。有3种不同的治疗方法。我想创建两个地块:R和ggplot - 情节分布和行

一个看起来是这样的:

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) 

我使用

​​

尝试,但它不工作。我能得到具有R要做的比例对我来说,最接近的是从另一篇文章下面的叠加柱状图使用代码:

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

就可以完成你的榜样?有部分缺失(如P是什么) – Heroka

+0

p将是每年t的百分比。在上面列出的DF中,2001年有4个观察值。 p(a)2001将是0.5,p(b)= 0.25,p(c)= 0.25等等,p每年会有所不同。谢谢。 –

+0

但这不是ggplot的工作原理。 Ggplot不会[数据] + [几何]。 – Heroka

回答

1

为您展示的图表类型,您就需要前后情节来计算比例。 table功能可用于按年计算ttavesumy然后计算比例的年度总和。你的第一个阴谋是用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) 

产生的田块 enter image description here

enter image description here

+0

非常感谢您的帮助 - 这是非常有用的,我能够创建我需要的情节。只是一个更新,我不得不删除'position =“stack”'来创建没有比例总和的线条图。 –