Two geom_points add a legend

前端 未结 4 1744
悲哀的现实
悲哀的现实 2020-11-29 06:45

I plot a 2 geom_point graph with the following code:

source(\"http://www.openintro.org/stat/data/arbuthnot.R\")
library(ggplot2)
ggplot() +
  geom_point(aes(         


        
4条回答
  •  北荒
    北荒 (楼主)
    2020-11-29 07:32

    Here is an answer based on the tidyverse package. Where one can use the pipe, %>%, to chain functions together. Creating the plot in one continues manner, omitting the need to create temporarily variables. More on the pipe can be found in this post What does %>% function mean in R?

    As far as I know, legends in ggplot2 are only based on aesthetic variables. So to add a discrete legend one uses a category column, and change the aesthetics according to the category. In ggplot this is for example done by aes(color=category).

    So to add two (or more) different variables of a data frame to the legends, one needs to transform the data frame such that we have a category column telling us which column (variable) is being plotted, and a second column that actually holds the value. The tidyr::gather function, that was also loaded by tidyverse, does exactly that.

    Then one creates the legend by just specifying which aesthetics variables need to be different. In this example the code would look as follows:

    source("http://www.openintro.org/stat/data/arbuthnot.R")
    library(tidyverse)
    
    arbuthnot %>%
        rename(Year=year,Men=boys,Women=girls) %>%
        gather(Men,Women,key = "Sex",value = "Rate") %>%
        ggplot() +
        geom_point(aes(x = Year, y=Rate, color=Sex, shape=Sex)) +
        scale_color_manual(values = c("Men" = "#3399ff","Women"= "#ff00ff")) +
        scale_shape_manual(values = c("Men" = 16, "Women" =  17))
    

    Notice that tidyverse package also automatically loads in the ggplot2 package. An overview of the packages installed can be found on their website tidyverse.org.

    In the code above I also used the function dplyr::rename (also loaded by tidyverse) to first rename the columns to the wanted labels. Since the legend automatically takes the labels equal to the category names.

    There is a second way to renaming labels of legend, which involves specifying the labels explicitly in the scale_aesthetic_manual functions by the labels = argument. For examples see legends cookbook. But is not recommended since it gets messy quickly with more variables.

提交回复
热议问题