📌  相关文章
📜  如何使用 ggplot2 在 R 中使用多行创建绘图?

📅  最后修改于: 2022-05-13 01:54:41.612000             🧑  作者: Mango

如何使用 ggplot2 在 R 中使用多行创建绘图?

在本文中,我们将讨论如何在 R 编程语言中使用多行的 ggplot2 创建绘图。

方法一:使用 geom_line()函数

在这种创建多行ggplot的方法中,用户需要首先在R控制台中安装并导入ggplot2包,然后以受尊重的参数组合调用ggplot()和geom_line()函数作为ggplot( )函数将有助于创建绘图,而 geom_line()函数将有助于创建线条,并且当 geom_line()函数多次调用多个数据时,会将倍数线条返回到 ggplot。

geom_line()函数:此函数用于连接观察,按 x 值排序。

例子:



在此示例中,我们将使用 R 编程语言中 ggplot2 包中的 geom_line函数在简单的 ggplot 上绘制五条具有不同数据和不同颜色线条的多条线。

R
library("ggplot2") 
  
  
gfg_data <- data.frame(x = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10),
                   y1 = c(1.1, 2.4, 3.5, 4.1, 5.9, 6.7, 
                          7.1, 8.3, 9.4, 10.0),
                   y2 = c(7, 5, 1, 7, 4, 9, 2, 3, 1, 4),
                   y3 = c(5, 6, 4, 5, 1, 8, 7, 4, 5, 4),
                   y4 = c(1, 4, 8, 9, 6, 1, 1, 8, 9, 1),
                   y5 = c(1, 1, 1, 3, 3, 7, 7, 10, 10, 10))
  
gfg_plot <- ggplot(gfg_data, aes(x)) +  
    geom_line(aes(y = y1), color = "black") +
     geom_line(aes(y = y2), color = "red") +
    geom_line(aes(y = y3), color = "green") +
    geom_line(aes(y = y4), color = "blue") +
    geom_line(aes(y = y5), color = "purple")
gfg_plot


R
library("reshape2")  
  
  
gfg_data <- data.frame(x = c(1,2,3,4,5,6,7,8,9,10),
                   y1 = c(1.1,2.4,3.5,4.1,5.9,6.7,
                          7.1,8.3,9.4,10.0),
                   y2 = c(7,5,1,7,4,9,2,3,1,4),
                   y3 = c(5,6,4,5,1,8,7,4,5,4),
                   y4 = c(1,4,8,9,6,1,1,8,9,1),
                   y5 = c(1,1,1,3,3,7,7,10,10,10))
  
data_long <- melt(gfg_data, id = "x")
gfg_plot <- ggplot(data_long,            
               aes(x = x,
                   y = value,
                   color = variable)) +  geom_line()
gfg_plot


输出:

方法二:使用reshape2包

在这种创建多行ggplot的方法中,用户需要首先在R控制台中安装并导入reshape2包,并调用带有所需参数的melt()函数将给定的数据格式化为长数据形式,然后使用ggplot()函数绘制格式化数据的 ggplot。

要在 R 控制台中安装和导入 reshape2 包,用户需要遵循以下语法:

install.packages("reshape2 ")      
library("reshape2 ")

melt()函数:这是通用的melt函数。有关不同数据结构的详细信息,请参阅以下函数:

示例:在此示例中,我们将使用 ggplot()函数在简单的 ggplot 上绘制五条具有不同数据和不同颜色线条的多条线,并将数据从 R 编程语言的 reshape 包中修改为长数据格式。

电阻

library("reshape2")  
  
  
gfg_data <- data.frame(x = c(1,2,3,4,5,6,7,8,9,10),
                   y1 = c(1.1,2.4,3.5,4.1,5.9,6.7,
                          7.1,8.3,9.4,10.0),
                   y2 = c(7,5,1,7,4,9,2,3,1,4),
                   y3 = c(5,6,4,5,1,8,7,4,5,4),
                   y4 = c(1,4,8,9,6,1,1,8,9,1),
                   y5 = c(1,1,1,3,3,7,7,10,10,10))
  
data_long <- melt(gfg_data, id = "x")
gfg_plot <- ggplot(data_long,            
               aes(x = x,
                   y = value,
                   color = variable)) +  geom_line()
gfg_plot

输出: