In ggplot2, how to choose which geom appears in le

2019-06-25 08:55发布

问题:

Some geom obscure the key to other geoms in the legend (notably, boxplot)

How can I choose which geom appears in the legend?

Eg.:

qplot(data=CO2,
      x=Type,
      y=uptake,
      colour=Plant,
      shape=Treatment)+
        geom_boxplot()

Switching the order of the geoms helps

qplot(data=CO2,
      x=Type,
      y=uptake,
      colour=Plant,
      shape=Treatment,
      geom="boxplot")+
        geom_point()

But I would like the legend found with:

qplot(data=CO2,
      x=Type,
      y=uptake,
      colour=Plant,
      shape=Treatment)

Do I need to extract the legend of one plot and paste it to the other using something like gridExtra?

回答1:

You can suppress the legend for the boxplot by adding show_guide=FALSE to the geom_boxplot() call. You still get the legend from the points.

qplot(data=CO2,
      x=Type,
      y=uptake,
      colour=Plant,
      shape=Treatment)+
        geom_boxplot(show_guide=FALSE)

If you were not already plotting points (that is, just had boxplot, but wanted the legend to be shown with points symbol rather than the boxplot symbol), that is harder, though I think possible.



标签: r ggplot2