2016-10-21 63 views
0

我想將兩個圖重疊放在另一個之上。這兩個圖共享相同的X軸和Y軸。唯一的區別是第一個圖是一個barplot,第二個是折線圖。合併兩個圖,以便圖例中的着色系列重合

library("ggplot2") 

p1 <- ggplot(result_a, aes(x=type,y=as.numeric(num_excluded),fill=as.factor(year),width=.5)) + 
    geom_bar(position = "stack", stat="identity")+ 
    coord_flip() 

p1 <- p1 + guides(fill=guide_legend(title="Legend:")) + 
    scale_fill_brewer(palette="Set1") 


p2 <- ggplot(result_a, aes(x=type,y=as.numeric(total), 
          group=as.factor(year),color=as.factor(year), 
          width=.5)) + 
    geom_line()+geom_point()+ 
    coord_flip() 

我怎樣才能把它們放在一起,這樣的線條和酒吧的顏色一致(即在一個給定的傳奇色彩的解釋是指兩條線和酒吧)?

更新:

dput(result_a)

structure(list(year = c(2011, 2011, 2011, 2012, 2012), type = c("AAA", "BBB", "AAA","BBB", "AAA"), num_excluded = c(5, 2, 4, 15, 2), total = c(100,20,500,300,100))) 
+0

您可以發佈一個'dput(result_a)'? –

+0

[This](http://stackoverflow.com/questions/40048002/represent-geom-line-and-geom-bar-in-the-same-plot)可能會有所幫助。對於顏色,您應該能夠將它們手動設置爲相同的調色板。 – Haboryme

+0

@MikeyMike:完成。 – FiofanS

回答

2

你的意思是某事像這樣?

ggplot(result_a) + 
    geom_bar(aes(x = type, y = as.numeric(num_excluded), 
       fill = as.factor(year), width=.5), position = "stack", stat = "identity") + 
    geom_line(aes(x = type, y = as.numeric(total), 
        group = as.factor(year), color = as.factor(year), 
        width = .5), size = 2) + 
    coord_flip()+ 
    guides(fill = guide_legend(title = "Legend:")) + 
    scale_fill_brewer(palette = "Set1") + 
    scale_color_brewer(palette = "Set1", guide = FALSE) 

enter image description here

+0

謝謝Marta。但是,我想將這些圖表合併到一個圖表中。因此,p2的行會在p1的頂部(或者更靠右的位置),如果使用'coord_flip()',你知道hw會這麼做嗎? – FiofanS

+0

@FiofanS,我已經編輯了我的答案。對於這樣的事情? – Marta

+0

是的,絕對!只是一個小細節:我也想分享這個傳奇和它的顏色,是否可以使用對應這兩個圖表的1個傳說? – FiofanS