rggplot2

R ggplot: force legend guide of separate geoms onto separate rows when using horizontal legend


I am creating a chart with two different geoms and would like to include them on separate rows (one row per geom) in a legend at the top of the chart. For example:


ggplot(data = iris) +
  geom_point(aes(x=Sepal.Length,

                           y=Sepal.Width,
                           color=Species)) + 
  geom_ribbon(aes(x=Sepal.Length,
                  ymin=2.5,
                  ymax=4,
                  fill = "flower"),
              alpha=0.2) +
  scale_fill_manual(name="Area",
                    values=c("flower"="green"))+
  theme(legend.position = "top")

Currently the legend for color and fill appear next to each other on the same row, so it seems the geoms have been assigned "columns".

plot with wrong legend However, I want the color legend below the fill legend, like:

plot with correct legend


Solution

  • Use theme:

    theme(legend.position = "top", legend.box = "vertical",
            legend.box.just = "left",
            legend.justification = "left") 
    

    enter image description here