簡體   English   中英

R和ggplot-圖分布和線

[英]R and ggplot - plot distribution and line

我有一個看起來很簡單的問題,但似乎無法弄清楚。 我有一個給定年份的治療數據集。 有3種不同的治療方法。 我想創建兩個圖:

看起來像這樣的一個:

面積圖

看起來像這樣的一個:

散點圖

,除了,我想堆疊多種處理方式(三種而不是示例中的一種)。

假設我們有以下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))

對於顯示的圖表類型,在繪制之前需要計算比例。 table功能可用於按年和tt進行計數。 ave with sum by 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)

產生地塊 在此處輸入圖片說明

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM