r - R 中多个变量的线图

标签 r graphics line-plot

我有以下格式的输入数据。

  x      y       z
  0      2.2     4.5
  5      3.8     6.8
  10     4.6     9.3
  15     7.6     10.5

我如何在 R 中绘制像 excel 一样的 xy 散点图(如下所示)?

enter image description here

最佳答案

至少有四种方法可以做到这一点:
(1) 在此处使用名为 df 的“horizo​​ntal”或“wide”data.frame

df <- data.frame(x = c(0, 5, 10, 15), y = c(2.2, 3.8, 4.6, 7.6),z = c(4.5, 6.8, 9.3, 10.5))
    
ggplot(df, aes(x)) + 
  geom_line(aes(y = y, colour = "y")) +   
  geom_line(aes(y = z, colour = "z"))
(2) 使用格子
library(lattice)
xyplot(x ~ y + z, data=df, type = c('l','l'), col = c("blue", "red"), auto.key=T)
(3)把你原来的df变成一个“长”的data.frame。这就是您在 ggplot2 中处理数据的通常方式
library(reshape)
library(ggplot2)

mdf <- melt(df, id="x")  # convert to long format
ggplot(mdf, aes(x=x, y=value, colour=variable)) +
    geom_line() + 
    theme_bw()
enter image description here
(4) 使用 matplot() 我还没有真正探索过这个选项,但这里有一个例子。
matplot(df$x, df[,2:3], type = "b", pch=19 ,col = 1:2)

关于r - R 中多个变量的线图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17562379/

相关文章:

algorithm - 点到面的最小距离

r - 在 R 中创建一个时间间隔为 5 分钟的 24 小时向量

r - 合并具有多个匹配项的数据框时仅选择第一行

java - 在 Android 上显示简单的位图

c++ - OpenGL 几何着色器三角形不会绘制没有错误

r - ggplot : lineplot of means of two groups

r - 连续变化的线宽在ggplot中变得透明

r - ggplot() 线条透明度

r - 通过 geom_point 和 ggtern 中的黑色轮廓填充

R:在 reshape2 中对行进行排序