ggplot2: Plotting multiple vectors sequentially

前端 未结 1 565
无人及你
无人及你 2021-01-25 11:24

Suppose I have two vectors, say

vec1 <- c(1,2,1,3)
vec2 <- c(3,3,2,4)

I want to plot both vectors in series, in different colors, on GGPl

相关标签:
1条回答
  • 2021-01-25 12:21

    We need to make a data frame from vec1 and vec2. Since ggplot2 prefers data in long format, we convert df to df_long using gather from the tidyr package (after creating id column using mutate function from the dplyr package). After that it's fairly easy to do the plotting.

    See this answer to learn more about changing the shape of the points

    library(dplyr)
    library(tidyr)
    library(ggplot2)
    
    vec1 <- c(1,2,1,3)
    vec2 <- c(3,3,2,4)
    
    df <- data.frame(vec1, vec2)
    df_long <- df %>% 
      mutate(id = row_number()) %>% 
      gather(key, value, -id)
    df_long
    
    #>   id  key value
    #> 1  1 vec1     1
    #> 2  2 vec1     2
    #> 3  3 vec1     1
    #> 4  4 vec1     3
    #> 5  1 vec2     3
    #> 6  2 vec2     3
    #> 7  3 vec2     2
    #> 8  4 vec2     4
    
    ggplot(df_long, aes(x = id, y = value)) +
      geom_point(aes(color = key, shape = key), size = 3) +
      theme_classic(base_size = 16)
    

    Created on 2018-08-08 by the reprex package (v0.2.0.9000).

    0 讨论(0)
提交回复
热议问题