FiofanS FiofanS - 1 month ago 6
R Question

Merge two plots so that coloring of series coincides in a legend

I want to put two plots one on top of another. Both of these plots share the same X and Y axis. The only difference is that the first plot is a barplot, and the second one is line chart.

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()


How can I put them together so that the COLORS of lines and bars coincide (i.e. the interpretation of colors given in a legend refers to both lines and bars)?

Update:

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)))

Answer

Do you mean sth like this?

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