2015-11-05 86 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」'來創建沒有比例總和的線條圖。 –