我想把两个地块放在另一个上面。这两个图都共享相同的X和Y轴。唯一的区别是第一个图是条形图,第二个图是折线图。
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 :(得分: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)