1

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 GGPlot. For example, to plot a single vector in series, I could simply do:

qplot(seq_along(vec1),vec1))

But I want to plot both in series, so we can pairwise compare the entries visually. The graph would look something like:

enter image description here

Thanks!

1
  • I would suggest looking at the ggplot documentation, essentially you just need a plot canvas with multiple stored vectors or if you convert the vectors in to a df you can just pass the df in. Commented Aug 8, 2018 at 17:36

1 Answer 1

3

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).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.