2016-05-12 77 views
0

我有欲沿兩個維度標繪數據:VK(離散)和relPrec(連續)傳奇用於GGPLOT2兩個離散秤

此外,我有沿兩個維度屬性:

type <- c("relPrecAir", "relPrecInv", "relPrectotal") 
p <- c(0.9, 0.95, 0.99) 

我想用顏色表示type,用顏色表示p。我設法使用以下代碼:

precisionTable <- structure(list(relPrecTotal = c(0, 0, 0, 0.0070300473755567, 0.00842647198124317, 0.0112374693913644), relPrecAir = c(0, 0, 0, 0.00700370093237813, 0.00839489217055491, 0.011195354831821), relPrecInv = c(0, 0, 0, 0.0108917034179065, 0.0130551941937278, 0.0174102928813975), p = c(0.9, 0.95, 0.99, 0.9, 0.95, 0.99), VK = c(0, 0, 0, 1.15, 1.15, 1.15), case = c("demandStochastic", "demandStochastic", "demandStochastic", "demandStochastic", "demandStochastic", "demandStochastic")), .Names = c("relPrecTotal", "relPrecAir", "relPrecInv", "p", "VK", "case"), row.names = c(NA, -6L), class = "data.frame") 

ggplot(precisionTable, aes(VK, relPrecTotal, color=as.factor(p))) + geom_line() + geom_point(shape=19) + 
        geom_line(aes(VK,relPrecAir, color=as.factor(p))) + geom_point(aes(VK,relPrecAir), shape=17) + 
        geom_line(aes(VK,relPrecInv, color=as.factor(p))) + geom_point(aes(VK,relPrecInv), shape=15) + 
         scale_color_discrete(name="p") 

顯示p的一個圖例。但是我無法用形狀值爲type繪製第二個圖例。我如何添加它?

My try, legend for shapes is missing

回答

1

我們可以通過添加新的分組的參數進行這項工作,relPrecAirrelPrecInv,然後繼續使用ggplot繪製它。

編輯重寫形狀色彩的傳奇

library(reshape2) 
precisionTable2 <- melt(precisionTable, measure.vars = c("relPrecTotal", "relPrecAir", "relPrecInv")) 
ggplot(precisionTable2, aes(VK, value)) + 
    geom_line(aes(color=as.factor(p), shape=as.factor(variable))) + 
    geom_point(aes(color=as.factor(p),shape=as.factor(variable))) + 
    scale_color_discrete(name='p') + 
    scale_shape_discrete(name='relPrec') + 
    guides(color=guide_legend(override.aes = list(shape=NA))) 

edit

+0

感謝,@ zyurnaidi,非常好!有沒有辦法從p下面的圖例中刪除點?嚴格地說,它們有點誤導,因爲只有顏色而不是形狀是重要的。 – mondano

0

你可以melt您data.frame,以避免在您ggplot命令的多個步驟,並創建一個新的變量(這裏ptShape),您將映射一個geom_point呼叫aes內:

library(reshape2) 
pmelt = melt(precisionTable, id.vars=c('VK', 'p', 'case')) 
pmelt$ptShape = rep(c(19,17,15), each=6) 

ggplot(pmelt, aes(x=VK, y=value)) + 
    geom_line(aes(colour=as.factor(p), shape=as.factor(ptShape))) + 
    geom_point(aes(colour=as.factor(p), shape=as.factor(ptShape)), size=5) 

enter image description here

+0

注意,我認爲這是你想要的東西,但它似乎是一個奇怪的結果對我;-) – ztl