ggplot2: Plotting multiple vectors sequentially

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



ggplot2: Plotting multiple vectors sequentially



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!





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.
– Mike Tung
Aug 8 at 17:36




1 Answer
1



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.


vec1


vec2


ggplot2


df


df_long


gather


tidyr


id


mutate


dplyr



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


shape


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






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

Creating a leaderboard in HTML/JS