2015-06-22 119 views
1

如何合併2個直方圖qplots並將它們放在同一個圖上而不是2個獨立的圖上?有一個關於簡單一維直方圖的類似問題:How to plot two histograms together in R? 但是,它們不使用qplots,而是使用簡單的一維直方圖。 以下是原始代碼。如果你可以修改它,讓直方圖的每個圖例都是左側的圖例,而另一個圖形右側的圖例將使我的一天。非常感謝!!!如何在R中合併兩個或多個二維直方圖?

plt_d = d[s & grepl("Rd", d$Cmd), c("Time_Stamp_Norm", 
    "Virtual_Address_Norm")] 

    p1 <- qplot(Time_Stamp_Norm, Virtual_Address_Norm, data=plt_d, 
    geom='bin2d', binwidth = hist_binwidth, 
    xlab="Normalized Time", 
    ylab="Normalized Address", 
    main="Read requests in virtual address space") + 
    scale_fill_gradient(low="#C6DBEF", high="#08306B") + 
    xlim(0, 1+b_inv) + ylim(0, 1+b_inv) + 
    theme(axis.text=element_text(size=10), axis.title=element_text(size=10), 
    plot.title=element_text(size=10)) 

    plt_d = d[s & grepl("Wr", d$Cmd), c("Time_Stamp_Norm", 
    "Virtual_Address_Norm")] 

    p2 <- qplot(Time_Stamp_Norm, Virtual_Address_Norm, data=plt_d, 
    geom='bin2d', binwidth = hist_binwidth, 
    xlab="Normalized Time", 
    ylab="Normalized Address", 
    main="Write requests in virtual address space") + 
    scale_fill_gradient(low="#C7E9C0", high="#00441B") + 
    xlim(0, 1+b_inv) + ylim(0, 1+b_inv) + 
    theme(axis.text=element_text(size=10), axis.title=element_text(size=10), 
    plot.title=element_text(size=10)) 

    ... 

    print(p1, vp = viewport(layout.pos.row = 1, layout.pos.col = 1)) 
    print(p2, vp = viewport(layout.pos.row = 1, layout.pos.col = 2)) 

    ... 

    dev.off() 

enter image description here

+0

看起來你需要的是一個變量代表什麼這兩個類別的每個數據點落入的;那麼你的填充美學就是由這個因素決定的,而alpha則由數字決定。這至少會在一組軸上得到兩個類別。但導遊會有點麻煩。 – tegancp

+0

謝謝。所有需要的是將綠色數據放在藍色的頂部,將綠色的圖例放在圖的左側。綠色不應該與藍色重疊(可能在一些小點),因爲它們可以及時分開。 – Dimon

回答

1

感謝tegancp的建議。這裏是我的解決方案:

x <- c(rnorm(n=1000, mean=5, sd=1), rnorm(n=1000, mean=7, sd=1)) 
y <- c(rnorm(n=1000, mean=5, sd=1), rnorm(n=1000, mean=7, sd=1)) 
d <- data.frame(x,y) 
d$type=c(rep("Rd",1000),rep("Wr",1000)) 
p <- ggplot(d) + geom_bin2d(aes(x=x, y=y, alpha=..count.., fill = d$type)) 
pdf(file="my_file.pdf") 
print(p) 
dev.off() 

enter image description here