2014-07-24 46 views
2

顯示傳說我有這樣的代碼ggplot不geom_histogram

ggplot() 
+ geom_histogram(aes(x=V1, y=(..count..)/sum(..count..)), fill="red", alpha=.4, colour="red", data=coding, stat = "bin", binwidth = 30) 
+ geom_histogram(aes(x=V1,y=(..count..)/sum(..count..)), fill="blue", alpha=.4, colour="blue", data=lncrna, stat = "bin", binwidth = 30) 
+ coord_cartesian(xlim = c(0, 2000)) 
+ xlab("Size (nt)") 
+ ylab("Percentage (%)") 
+ geom_vline(data=cdf, aes(xintercept=rating.mean, colour=Labels), linetype="dashed", size=1) 

產生一個美麗的直方圖沒有傳說:

enter image description here

在每一個崗位我同樣的問題參觀,他們說把color放入aes。不過,這並沒有給出任何傳說。

我想:

ggplot() + geom_histogram(aes(x=V1, y=(..count..)/sum(..count..),color="red", fill="red"), fill="red", alpha=.4, colour="red", data=coding, stat = "bin", binwidth = 30) 
+ geom_histogram(aes(x=V1,y=(..count..)/sum(..count..), color="blue", fill="blue"), fill="blue", alpha=.4, colour="blue", data=lncrna, stat = "bin", binwidth = 30) 
+ coord_cartesian(xlim = c(0, 2000)) 
+ xlab("Size (nt)") 
+ ylab("Percentage (%)") 
+ geom_vline(data=cdf, aes(xintercept=rating.mean, colour=Labels), linetype="dashed", size=1) 

沒有成功。

我該如何在圖表中添加圖例?

+1

您是否嘗試在審美映射中指定填充/顏色?我沒有看到你的代碼。一些[示例數據](http://stackoverflow.com/a/5963610/1412059)可以讓你更容易地向你展示如何做到這一點。 – Roland

+0

什麼是審美映射? – user2979409

+0

@ user2979409:這是您使用的'aes()'函數。 –

回答

4

問題是,你不能將你的顏色映射到aes,因爲你有兩個單獨的數據集。一個想法是綁定它們,然後應用package reshape2的「融合」功能,以便創建一個虛擬分類變量,您可以將其傳遞給aes。驗證碼:

require(reshape2) 
df=cbind(blue=mtcars$mpg, red=mtcars$mpg*0.8) 
df=melt(df, id.vars=1:2) 
ggplot()+geom_histogram(aes(y=(..count..)/sum(..count..),x=value, fill=Var2, color=Var2), alpha=.4, data=df, stat = "bin") 

有你有你的傳說

+1

re:使用這個,你的酒吧將被閃避或堆疊,但你可以調整位置參數來疊加酒吧:「position = position_dodge(width = 0)」 – agenis

7

如果你不想把數據放到一個data.frame,你可以這樣做:

set.seed(42) 
coding <- data.frame(V1=rnorm(1000)) 
lncrna <- data.frame(V1=rlnorm(1000)) 


library(ggplot2) 
ggplot() + 
    geom_histogram(aes(x=V1, y=(..count..)/sum(..count..), fill="r", colour="r"), alpha=.4, data=coding, stat = "bin") + 
    geom_histogram(aes(x=V1,y=(..count..)/sum(..count..), fill="b", colour="b"), alpha=.4, data=lncrna, stat = "bin") + 
    scale_colour_manual(name="group", values=c("r" = "red", "b"="blue"), labels=c("b"="blue values", "r"="red values")) + 
    scale_fill_manual(name="group", values=c("r" = "red", "b"="blue"), labels=c("b"="blue values", "r"="red values")) 

enter image description here

+0

能從輸出中刪除圖例名稱嗎? – simone

+0

只需傳遞一個空字符串... – Roland