如何使用 R 中的 ggplot2 为数据帧子集创建一个线形图?
子集是 R 中一件不困难的事,但如果我们把自己的代码写的短一些,那么这是一个很繁琐的任务,因为我们必将在代码之间插入代码,这会造成混乱。所以,我们在一个代码中写另外一个代码时必须非常小心。通过使用 ggplot2 的 ggplot 函数,可以使用子集函数来创建使用子集数据帧的直线。
示例
考虑下面的数据帧 -
set.seed(99)
x1<-rep(c("Sample1","Sample2","Sample3","Sample4"),times=5)
x2<-rpois(20,5)
x3<-runif(20,2,5)
df<-data.frame(x1,x2,x3)
df输出
x1 x2 x3
1 Sample1 5 2.683710
2 Sample2 2 2.241572
3 Sample3 6 4.464855
4 Sample4 11 3.773342
5 Sample1 5 4.320167
6 Sample2 9 3.050258
7 Sample3 6 2.018184
8 Sample4 4 4.443519
9 Sample1 4 2.003538
10 Sample2 3 2.602071
11 Sample3 5 3.500318
12 Sample4 5 2.970510
13 Sample1 3 3.040351
14 Sample2 6 3.636462
15 Sample3 6 2.121470
16 Sample4 6 3.331542
17 Sample1 4 4.072941
18 Sample2 2 4.471554
19 Sample3 2 3.820360
20 Sample4 3 4.932325
library(ggplot2)
ggplot(subset(df,x1 %in% c("Sample2","Sample3")))+
+ geom_line(aes(x2,x3,group=x1,colour=x1))输出

ggplot(subset(df,x1 %in% c("Sample1","Sample4")))+
+ geom_line(aes(x2,x3,group=x1,colour=x1))输出

为三个样本(Sample1、Sample2 和 Sample3)创建绘图 -
ggplot(subset(df,x1 %in% c("Sample1","Sample2","Sample3")))+
+ geom_line(aes(x2,x3,group=x1,colour=x1))输出

广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP