Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
786 views
in Technique[技术] by (71.8m points)

r - 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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...