R语言 使用ggplot2从数据框架列表中绘制线条
在这篇文章中,我们将讨论如何在R编程语言中用ggplot从数据帧的列表中绘制线条。
ggplot2软件包被用来可视化和分析数据。该软件包可以在R语言中使用以下命令下载和安装。
install.packages("ggplot2")
R中的ggplot方法是用来使用指定的数据框架进行图形可视化的。它被用来实例化一个ggplot对象。可以为绘图对象创建美学映射,以分别确定x轴和y轴之间的关系。可以向创建的ggplot对象添加其他组件。
语法: ggplot(data = NULL, mapping = aes(), color())
参数 :
- data – 用于绘图的默认数据集。
- mapping – 用于绘图的审美贴图列表。
Geoms可以用各种方法添加到绘图中。R中的geom_line()方法可以用来在绘制的图中添加图形线。它被作为一个组件添加到现有的绘图中。美学映射也可以包含颜色属性,根据不同的数据框架以不同的方式分配。geom_line()方法的语法如下:
geom_line()
例1 :
# importing required libraries
library("dplyr")
library("ggplot2")
# creating the dataframes
df1 = data.frame(col1=c(1: 10), col2=rnorm(10))
df2 = data.frame(col1=c(5: 10), col2=rnorm(6))
df3 = data.frame(col1=c(2: 12), col2=rnorm(11))
# creating a list of dataframes
samplelist = list(df1, df2, df3)
# plotting the data
graph < - ggplot(bind_rows(samplelist, .id="data_frame"),
aes(col1, col2, colour=data_frame)) +
geom_line()
# printing the graph
print(graph)
输出
[1] "First Dataframe"
> print(df1)
col1 col2
1 1 2.6799001
2 2 1.6732359
3 3 -0.2821830
4 4 0.6951255
5 5 0.3629730
6 6 1.6543411
7 7 0.9301622
8 8 0.6858366
9 9 1.3150289
10 10 -0.9306804
> print("Second Dataframe")
[1] "Second Dataframe"
> print(df2)
col1 col2
1 5 -0.1813050
2 6 1.3543525
3 7 0.0810269
4 8 0.1788353
5 9 1.5264921
6 10 0.3677910
> print("Third Dataframe")
[1] "Third Dataframe"
> print(df3)
col1 col2
1 2 -1.0602057
2 3 -0.6040208
3 4 1.9346507
4 5 0.5183120
5 6 0.7176499
6 7 0.2908290
7 8 1.4760342
8 9 0.5935123
9 10 0.3882407
10 11 0.8871490
11 12 -0.3974801
例2 :
# importing required libraries
library("dplyr")
library("ggplot2")
# creating the dataframes
df1 = data.frame(col1=c(1: 10), col2=letters[1:5])
df2 = data.frame(col1=c(7: 9), col2=letters[5:7])
df3 = data.frame(col1=c(1: 6), col2=rep('e', 6))
df4 = data.frame(col1=c(5, 9, 10), col2=c('x', 'm', 'n'))
print("First DataFrame")
print(df1)
print("Second DataFrame")
print(df2)
print("Third DataFrame")
print(df3)
print("Fourth DataFrame")
print(df4)
# creating a list of dataframes
samplelist = list(df1, df2, df3, df4)
# plotting the data
graph < - ggplot(bind_rows(samplelist, .id="data_frame"),
aes(col1, col2, colour=data_frame)) +
geom_line()
# printing the graph
print(graph)
输出
[1] "First DataFrame"
> print(df1)
col1 col2
1 1 a
2 2 b
3 3 c
4 4 d
5 5 e
6 6 a
7 7 b
8 8 c
9 9 d
10 10 e
> print ("Second DataFrame")
[1] "Second DataFrame"
> print(df2)
col1 col2
1 7 e
2 8 f
3 9 g
> print ("Third DataFrame")
[1] "Third DataFrame"
> print(df3)
col1 col2
1 1 e
2 2 e
3 3 e
4 4 e
5 5 e
6 6 e
> print ("Fourth DataFrame")
[1] "Fourth DataFrame"
> print(df4)
col1 col2
1 5 x
2 9 m
3 10 n