本文介绍了ggplot2:依次绘制多个向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两个向量

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

我想在GGPlot上以不同的颜色连续绘制两个向量.例如,要绘制单个矢量序列,我可以简单地做到:

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:

谢谢!

推荐答案

我们需要根据vec1vec2创建数据帧.由于ggplot2更喜欢长格式的数据,因此我们使用tidyr包中的gatherdf转换为df_long(在使用dplyr包中的mutate函数创建id列之后).之后,进行绘制就相当容易了.

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.

请参阅以下答案,以了解有关更改点的shape的更多信息

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)

reprex软件包(v0.2.0.9000)创建.

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

这篇关于ggplot2:依次绘制多个向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 04:21