2016-05-17 18 views
0

我使用ggplot2繪製X軸上的連續變量與Y軸上的相應計數(不是密度)的關係。如何填寫ggplot2 geom_freqpoly圖中的行下面的區域?

這是我的代碼

p <- ggplot(matched.frame, aes(x = AGE, color = as.factor(DRUG_KEY))) + geom_freqpoly(binwidth=5) 
p1 <- p + theme_minimal() 
plot(p1) 

這會產生這樣的這樣一個圖:

enter image description here

我想在這些線路的區域充滿色彩和透明度點點。我知道要做ggplot2中的密度圖,但我堅持使用這個頻率多邊形。

另外,如何更改右側的傳說?例如,我想'Cases'而不是26和Controls而不是'27'。取而代之的as.factor(DRUG_KEY),我希望它顯示爲「顏色」

的樣本數據

matched.frame <- data.frame("AGE"=c(18,19,20,21,22,23,24,25,26,26,27,18,19,20,24,23,23,23,22,30,28,89,30,20,23)) 
matched.frame$DRUG_KEY <- 26 
matched.frame$DRUG_KEY[11:25] <- 27 
+0

請給您的R問題添加可重複的例子。這使事情變得更容易。因此,您可能需要閱讀(1)[我如何提出一個好問題](http://stackoverflow.com/help/how-to-ask),(2)[如何創建MCVE](http: (3)[如何在R中提供最小可重現的示例](http://stackoverflow.com/questions/5963269/how-to-make-a-great- R-重複性,例如#答案-5963610)。 – lukeA

回答

1

您可以使用geom_ribbon曲線下,以填補區域和scale_fill_discrete(補色)以及scale_color_discrete(線顏色)更改圖例標籤:

library(ggplot2) 
set.seed(1) 
df <- data.frame(x = 1:10, y = runif(20), f = gl(2, 10)) 
ggplot(df, aes(x=x, ymin=0, ymax=y, fill=f)) + 
    geom_ribbon(, alpha=.5) + 
    scale_fill_discrete(labels = c("1"="foo", "2"="bar"), name = "Labels") 

至於你的編輯:

ggplot(matched.frame, aes(x=AGE, fill=as.factor(DRUG_KEY), color=as.factor(DRUG_KEY))) + 
    stat_bin(aes(ymax=..count..,), alpha=.5, ymin=0, geom="ribbon", binwidth =5, position="identity", pad=TRUE) + 
    geom_freqpoly(binwidth=5, size=2) + 
    scale_fill_discrete(labels = c("26"="foo", "27"="bar"), name = "Labels") + 
    scale_color_discrete(labels = c("26"="foo", "27"="bar"), name = "Labels") 
+0

這並沒有給我預期的結果。 Y軸必須是計數。 – technOslerphile

+0

提供一個可重現的例子,人們可以建立。 'y'是計數(解釋的問題)。 – lukeA

+0

添加了一個樣本數據,類似於我已經添加了一個例子 – technOslerphile

相關問題