Side by Side plot with one legend in ggplot2

Put your data together and use facets:

## calling the first data `melted_F` and the second `melted_F2`
## put them in one data frame with a column named "data" to tell
## which is which
melted = dplyr::bind_rows(list(data1 = melted_F, data2 = melted_F2), .id = "data")

## exact same plot code until the last line
ggplot(melted, aes(x=time, y=value, group = variable)) +
  geom_area(aes(fill=variable)) +
  scale_fill_manual(values=c("#2E318F", "#DFAE41","#109FC6"),
                    name="Asset Type",
                    labels = c("Bank account","Bonds", "Stocks"))+
  scale_x_continuous(name = 'Age',
                     breaks = seq(1,H,1)) + 
  scale_y_continuous(name = 'Asset allocation (in %)',
                     breaks = seq(0,1,0.1),
                     sec.axis = sec_axis(~.*1,breaks =  seq(0,1,0.1),labels=scales::percent)) + 
  coord_cartesian(xlim = c(1,H), ylim = c(0,1), expand = TRUE) +
  theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()) +
  ##  facet by the column that identifies the data source
  facet_wrap(~ data)

enter image description here

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top