R语言 的并排折线图

R语言 的并排折线图

在这篇文章中,我们将讨论如何在R编程语言中制作并排的折线图。

方法1:使用par()函数

在这里,我们将使用par()函数将框架划分为网格。

语法: par(mfrow, mar, mgp, las)

参数

  • mfrow: 一个长度为2的数字向量,它设定了要分割的框架的行和列。
  • mar: 一个长度为4的数字向量,按以下顺序设置边距大小:底部、左侧、顶部和右侧。
  • mgp : 一个长度为3的数字向量,用于设置相对于内部绘图窗口边缘的轴标签位置。
  • las: 一个数字值,表示刻度线标签和初始化后添加到绘图中的任何其他文本的方向。

在这里,通过改变行和列的数值,我们可以在其中绘制图形。对于绘制并排的图,我们将保持行为1,列为所需的图的数量。

# Define data-set columns
x1 <- c(31,13,25,31,16)
x2 <- c(12,23,43,12,22,45,32) 
  
# set the plotting area into a 1*2 array
par(mfrow = c(1, 2))    
  
# Draw the two line chart using above datasets
plot(x1, type="o", col="green")
plot(x2, type="o", col="blue")

输出

R语言中的并排折线图

方法2:使用ggplot2

在这里,我们将使用gridExtra包含的一个名为arrange()的函数,用于按需要安排绘图 。

语法: grid.arrange(plot, nrow, ncol)

参数

  • plot: 我们要安排的ggplot2绘图
  • nrow: 行的数量
  • ncol: 列的数量

在这里,通过改变nrow和ncol的值,我们可以在其中绘制图形。为了绘制并排的图,我们将保持nrow为1,ncol为所需的图的数量。

# Define data-set columns
x1 <- c(31,13,25,31,16)
x2 <- c(12,23,43,12,22,45,32) 
x3 <- c(234,123,210)
  
label1 <- c('geek','geek-i-knack',
            'technical-scipter',
            'content-writer','problem-setter')
  
label2 <- c('sun','mon','tue',
            'wed','thur','fri','sat') 
  
label3 <- c('solved','attempted','unsolved')
  
# Create data frame using above data column
data1 <- data.frame(x1,label1)
data2 <- data.frame(x2,label2)
data3 <- data.frame(x3,label3)
  
# set the plotting area into a 1*3 array
par(mfrow = c(1, 3))
  
# import library ggplot2 and gridExtra
library(ggplot2)
library(gridExtra)
  
# Draw the three line
# chart using above datasets
plot1<-ggplot(data1,
              aes(x=label1, y=x1, group=1)) +
geom_line()+ geom_point()
plot2<-ggplot(data2, aes(x=label2, y=x2, group=1)) +
geom_line(linetype = "dashed")+ geom_point()
  
plot3<-ggplot(data3, aes(x=label3, y=x3, group=1)) +
geom_line(color="green")+ geom_point()
  
# Use grid.arrange to put plots in columns
grid.arrange(plot1, plot2, plot3, ncol=3)

输出

R语言中的并排折线图

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程